Mihai Stan
Mihai Stan

Reputation: 153

Issue with JSON serialization in Unity

I'm trying to serialize an array of custom Monobehaviours, using JSON. I know it can't be done directly, so I'm using a wrapper class and serializing that instead.

This is the wrapper object

[System.Serializable]  
public class WavesCollection {
public Wave[] waves;
}


That's the object being wrapped (only the important bits of it)

[System.Serializable]
public class Wave : MonoBehaviour {
[SerializeField]public float[] AppearTimes;//at that time should the n-th enemy appear;
[SerializeField]public Vector2[] positions;//where should the n-th enemy appear;
[SerializeField]public EnemyType[] EnemiesToAppear;//what enemies should appear
}



        wavesArray = new Wave[] {thisWave, thisWave, thisWave};
WavesCollection collection = new WavesCollection();
collection.waves = new Wave[10];
wavesArray.CopyTo(collection.waves, 0);
StreamWriter sw = File.CreateText(WritePath);
string json = JsonUtility.ToJson(collection);
sw.WriteLine(json);
sw.Close();


And that's the code that does the serializing. Basically I've got an array of non-null Wave objects and I copy that to the wrapper object. I then try to write that in a file and the output is

{"waves":[{"instanceID":-99992},{"instanceID":-99992},{"instanceID":-99992},{"instanceID":0},{"instanceID":0},{"instanceID":0},{"instanceID":0},{"instanceID":0},{"instanceID":0},{"instanceID":0}]}


Could anyone give me a few directions on what I'm doing wrong?

Upvotes: 1

Views: 2796

Answers (1)

Life Alchemist
Life Alchemist

Reputation: 11

I had the same issue while inheriting my base class (Wave in your case) with scriptable object and that gave me the same issue. I could put in a single object and pass that in just fine, but got problematic instance id's in a list. I removed all forms of inheritance on the base class and it worked.

Upvotes: 1

Related Questions