I wanted to know how I can make my own custom 2 dimensional enum array class. I found a similar article online and here’s what I’ve come up with:
public enum myEnum { value1, value2, value3, value4, value5 };
[System.Serializable]
public class myClass {
public int columns = 9;
public int rows = 9;
public myEnum[] myArray = new myEnum [ columns * rows ];
public myEnum this [ int x, int y ] {
get {
return myArray [y * columns + x];
} set {
myArray [y * columns + x] = value;
}
}
}
Now I can call my array like this:
myClass myNewClass = new myClass ();
myNewClass [2,5] = myEnum.value3 // Set value
Instead of using myNewClass [2,5]
I wanted to use myNewClass.myArray [2,5]
. How do I go about doing that? I don’t want to use Unity’s original multidimensional method since it doesn’t serialize in the inspector.
That’s not possible unless your “myArray” is actually a custom class / struct which provides an indexer. Indexer can only be defined in classes / structs.
You can create a class like this:
[System.Serializable]
public class Serializable2DimArray<T>
{
private int m_Columns = 1;
[SerializeField]
private T[] m_Data;
public T this [ int aCol, int aRow ]
{
get { return m_Data[aRow * m_Columns + aCol]; }
set { m_Data[aRow * m_Columns + aCol] = value; }
}
public int Columns {get { return m_Columns; }}
public int Rows { get { return m_Data.Length / m_Columns; }}
public Serializable2DimArray(int aCols, int aRows)
{
m_Columns = aCols;
m_Data = new T[aCols * aRows];
}
}
With this struct you can simply declare a serializable 2-dimensional array for any type. Something like this:
[System.Serializable]
public class MyEnum2DimArray : Serializable2DimArray<myEnum> { }
This “type” can be used in any other serializable class just like a normal 2 dim array. The only exception is that you would create an array with “method brackets” instead of index brackets:
public MyEnum2DimArray myArray = new MyEnum2DimArray(2, 3);
Of course when you want to edit this array in the inspector you most likely need a propertydrawer for this class. The array length always has to be a multiple of the column count. Though it’s not clear for what purpose you actually need this 2dim array. It’s difficult to actually display a 2dim array if you have a large column count