I am trying to declare a public multidimensional array that I can access through the editor. However it would appear that only single dimension arrays are usable through the property inspector. Am I declaring these wrong, or are multidimensional arrays just not usable in the inspector?
I’m working up a prototype for a game that has gameobject tiles within a rectangular grid of [row, col]. The tiles exist in the scene and I need to assign references them to a tile controller. The controller will apply changes to all tiles in one row or one column while leaving the rest of the tiles alone.
I suppose I could declare a 1D array and set up methods for getting / setting row and col for the tiles, but that’s a huge pain in the ass.
Something like:
int GetArrayIndex(row, col)
{
return (row + col*numRows);
}
Using a 1-d array with access functions for 2-d indexing is actually a pretty common solution to this problem, and has the advantage of (potentially) better cache coherency and less fragmentation (although that may not matter in this context).
However, I think you can probably get the effect of a ‘real’ 2-d array by creating an array of objects, each of which represents one row. I tried the following:
[System.Serializable]
public class Row
{
public int[] data;
};
public Row[] test = new Row[3];
And it seemed to work. (I haven’t tried it, but by overloading the [ ] operator for the Row class, you may even be able to get the effect of ‘standard’ 2-d indexing, e.g. map[2][2].)
You can streamline it by allowing Jagged array syntax:
[System.Serializable]
public class StringArray
{
public string[] names;
public string this [int index]
{
get
{
return names[index];
}
set
{
names[index] = value;
}
}
};
public class TestClass : MonoBehaviour
{
StringArray[] stringArrayTest;
// Use this for initialization
void Start () {
Debug.Log(stringArrayTest[0][2]);
}
}
It’s a small feature and workaroundable, but It makes them easier to reference within code in my opinion.
I don’t have any useable samples because I’m working with iPhone, but if you want to use Generics you could also probably even work in a Generic serializable ArrayLayer, making it able to make 2D,3D,4D,nD arrays of any type you want with a single class.
Out of interest, has anyone managed to get this generic version working with the inspector? Using the strictly typed version with int works a treat, as soon as I replace it with a class that is exactly the same but has it’s int type replaced with a generic parameter (which is then set to int for the instance declaration) the inspector no longer displays the array.
public class RateRow {
[HideInInspector]
public string rate_name;
public Vector2[] rate_vector;
}
I found out you can add a public string to the row class, then hide it after it is set, and then each Element tag will be renamed to whatever you name it in inspector as well.