- Home /
2D array generated with custom inspector, null when starting game?
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?
How exactly do you use your Array? How do you fill it in the Editor? What do you want to do with it?
@ChrisAngel$$anonymous$$indmapfreak hi, sorry for the delayed response, I mustve missed the email.
I have a 2D array that is given data when pressing a button made from a custom inspector. For some reason the data is only available during the function called by the button. After that, it becomes null :(
I think I may have experienced the same problem before, however it was not specific to an array but rather to a custom class that was changed custom inspector.
I believe it has something to do with the way the Unity Editor serializes data. So, you could try two things: 1. $$anonymous$$ake the data not serialize (if you have the [Serializable] argument, remove it) 2. Use the [HideInInspector] to, well, hide variables.
Answer by Bunny83 · Jun 26, 2016 at 10:32 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220612083649im_/https://answers.unity.com/themes/thub/images/avi.jpg)