Hey, I started making a simple game with unity just for fun, but I think I may have hit a roadblock. I have a generated 2D array of tile GameObjects, and using that variable works fine when in edit mode. However, when I start the game, that variable goes null. I know this is probably a “works-as-intended” feature, but how can I get around this?
2D arrays can’t be serialized by Unity. You basically have two options:
- use a 1d array of a custom class which contains another 1d array
- use a “flattend” 1d array.
Example for the first case:
//C#
[System.Serializable]
public class SubArray
{
public GameObject[] objs;
}
public class SomeScript : MonoBehaviour
{
public SubArray[] array;
}
This is basically like a “jagged” array (a nested array) but it’s serializable by Unity. You can access an element like this:
GameObject o = array[dim0Index].objs[dim1Index];
The other solution is to use a flattend array. For this all you need is an additional integer variable that specifies the “width” of the 2d array:
public int arrayWidth = 10;
public GameObject[] array;
To access an element you just have to calculate the appropriate index manually. You can implement a get and set method for it:
public GameObject GetElement(int xIndex, int yIndex)
{
int index = xIndex + yIndex * arrayWidth;
return array[index];
}
public void GetElement(int xIndex, int yIndex, GameObject val)
{
int index = xIndex + yIndex * arrayWidth;
array[index] = val;
}
To create the array you just have to multiply your desired xSize with the ySize of the array:
public void CreateArray(int xSize, int ySize)
{
array = new GameObject[xSize * ySize];
arrayWidth = xSize;
}
The 1D array can be serialized by Unity.