0
votes

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?

1
What is your exception?Kevin Wallis
No exceptions are thrown. The problem is that the wrong things are being serialized.Mihai Stan
Why you inherited Wave class from MonoBehaviour? Please try without inheritance.Barış Çırıka
I've already managed to serialize Wave objects directly, as in turning a single Wave object into a single JSON, and that works just fine. The problem comes when I try to serialize an array of Wave objects. Therefore, I believe that inheriting from MonoBehaviour shouldn't cause issues.Mihai Stan

1 Answers

0
votes

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.