Search code examples
arraysunity-game-enginejagged-arrays

How to show a jagged array in Unity3d inspector?


I want to make a jagged array to order a group of waypoint systems. My problem is that I don't know how to show the jagged array in the Unity inspector so that I can fill the different arrays with the game objects I want (basically, squares of a board game).

The game is a board game with different paths the players can choose from (e.g Mario Party). In order to do so, instead of making a typical lineal waypoint system (from A to B) I thought about making several waypoint systems so the players can 'jump' from one waypoint system to another when they arrive to an intersection. As I wrote, I don't know how to show the jagged array in the inspector so that I can work properly. I tried to put [system.serializable] over the script class, but it doesn't work, the arrays simply don't appear.

public Transform[][] waypointSystems = new Transform[][] 
    {
      new Transform[1],
      new Transform[43],
      new Transform[1],
      new Transform[5],
      new Transform[7]
    };

Solution

  • Quick answer: You can't that simple. Muktidimesnional and jagged arrays are not serialized.

    One way could be to wrap one dimension of the array in another class like

    [Serializable]
    public class TransformArray
    {
        public Transform[] Array;
    
        public TransformArray(Transform[] array)
        {
            Array = array;
        }
    }
    
    public TransformArray[] waypointSystems = new TransformArray[]
    {
        new TransformArray(new Transform[1]),
        new TransformArray(new Transform[43]),
        new TransformArray(new Transform[1]),
        new TransformArray(new Transform[5]),
        new TransformArray(new Transform[7])
    };
    

    Alternatively you can write a [CustomEditor] but that there it gets really complex. You might be interested in this post

    or try to implement your own inspector usig the code snippet from this thread as a Startpoint

    SerializedProperty data = property.FindPropertyRelative("rows");
    for (int x = 0; x < data.arraySize; x++) 
    {
       // do stuff for each member in the array
       EditorGUI.PropertyField(newPosition, data.GetArrayElementAtIndex(x), GUIContent.none);
    }