3D Class Array cleared on script save

I have a 3D class array DataPoint[,] that is always cleared on change/save/recompile of scripts.

Parent script:

using UnityEngine;
using System.Collections;

public class ParentScript : MonoBehaviour {
	
	public ChildScript[] terrainVoxels = new ChildScript[0];
}

Child Script:

using UnityEngine;
using System.Collections;

[System.Serializable]
public class ChildScript : System.Object {

	public DataPoint[,,] terrainData = new DataPoint[0,0,0];
}

Data Point Script:

using UnityEngine;
using System.Collections;

[System.Serializable]
public class DataPoint : System.Object {

	public int status;
}

Inside the original version of the script, I define the ChildScript array correctly using editor scripts and I get no errors, and the array keeps its contents before/after script change. I also assign DataPoint array correctly and get no errors, but when I save/change a script after the contents are changed, array DataPoint[,] terrainData is cleared completely. Is there any way to fix this?

Unity’s serialization system doesn’t support multi-dimensional arrays. You can use them at runtime without any problems, but whenever the containing instance is serialized the array will be missed out. So when the instance is deserialized the array will have it’s default value which is in your case an empty array instance.

When Unity recompiles a script it has to completely destroy and shutdown the mono environment. Before Unity does that it serializes everything (including editor windows, inspectors, gameobject instances …). Once the assemblies are recompiled they are loaded again and all objects are recreated and deserialized from the temporary serialized data to restore the old state.

This procedure can only survive objects which are serializable by Unity.

For more information see the documentation. Unfortunately they don’t mention the dimension limit in the current documentation. Only one-dimensional arrays can be serialized. However you can create some sort of jagged array by using custom serializable classes:

[System.Serializable]
public class ChildScript 
{
    public Dim1[] items;
}

[System.Serializable]
public class Dim1
{
    public Dim2[] items;
}

[System.Serializable]
public class Dim2
{
    public DataPoint[] items;
}

It’s quite ugly but this construct will be serializable by Unity. Fields which are serializable by Unity don’t need to be initialized manually as the Inspector will automatically initialize the instances / arrays and you can change the item count in the inspector.