Why are certain script variable values set in the AssetPostprocessor being lost?

I have a script attached to a GameObject. The simplified script code looks like this:

public class MyScript : MonoBehaviour 
    public int       int_test         = 0;
    public int[]     intarray_test    = null;
    public ArrayList arraylist_test   = null;
    public float     float_test       = 0;
    public object    object_test      = null;
    public object[]  objectarray_test = null;
    public string    string_test      = null;

    void Start () {}
    void Update () {}

On asset import, I assign data to the variables in the script objects like this:

public class MyAssetProcessor : AssetPostprocessor 
    void OnPostprocessModel(GameObject g)
        Object[] scripts = GameObject.FindObjectsOfType( typeof( MyScript ) );
        foreach( MyScript script in scripts )
			script.int_test         = 1234567;
			script.intarray_test    = new int[2];
			script.arraylist_test   = new ArrayList();
			script.float_test       = 0.1234567f;
			script.object_test      = "object";
			script.objectarray_test = new object[2];
			script.string_test      = "string";

Once I start the game and hit a breakpoint in the Start function of MyScript, only some variables kept their values and some got lost:

alt text

Looks like only value types, other than the string, survived.


The key point here is that some of these types are compatible with Unity’s inbuilt serialization, and others are not.

You may have noticed the correlation between the variables which show up in the inspector, and the variables which are getting saved here. As you can see, the only types that lose their values are the ones that don’t show up in the inspector!

This is no coincidence. Because of the way Unity stores / restores objects in the Start step, the object will get destroyed and then rebuilt from the serialized data- and so, you lose any information that can’t be saved.

If you absolutely need those types, I recommend that you write a serializable wrapper for them, that Unity can use to store the information required for them. I’ve done similar things for jagged/multidimensional arrays in the past (these are another kind of object that Unity can’t serialize).