Skip to content

Matrix 2D

The serializable 2D matrix allows you to have an array of arrays (where all rows and columns have the same size) and the structure can be serialized in order to persist in the Inspector or saving the game.

To create a serializable matrix, simply inherit from TSerializableMatrix2D<T>. For example, to create a matrix that uses GameObject:

[Serializable]
public class MyMatrix : TSerializableMatrix2D<GameObject>
{
    public MyMatrix() : base()
    { }

    public MyMatrix(int width, int height) : base(width, height)
    { }
}

You can now create a matrix that automatically serializes its values:

public class MyComponent : MonoBehaviour
{
    public MyMatrix matrix = new MyMatrix(10, 5);

    private void Awake()
    {
        // Add element:
        this.matrix[2, 3] = this.gameObject;

        // Print element added
        Debug.Log(this.matrix[2, 3].name);
    }
}

The MatrixWidth and MatrixHeight properties return the size of the matrix. To safely read a position that may be out of bounds, use the TryGet(...) method, which returns false instead of throwing an exception:

if (this.matrix.TryGet(20, 20, out GameObject value))
{
    Debug.Log(value.name);
}