Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Issue with JSON serialization

Discussion in 'Scripting' started by StanMihai72, Jul 1, 2016.

  1. StanMihai72

    StanMihai72

    Joined:
    Apr 8, 2015
    Posts:
    6
    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
    Code (CSharp):
    1. [System.Serializable]  
    2. public class WavesCollection {
    3.     public Wave[] waves;
    4. }
    That's the object being wrapped (only the important bits of it)
    Code (CSharp):
    1. [System.Serializable]
    2. public class Wave : MonoBehaviour {
    3.     [SerializeField]public float[] AppearTimes;//at that time should the n-th enemy appear;
    4.     [SerializeField]public Vector2[] positions;//where should the n-th enemy appear;
    5.     [SerializeField]public EnemyType[] EnemiesToAppear;//what enemies should appear
    6. }
    Code (CSharp):
    1.         wavesArray = new Wave[] {thisWave, thisWave, thisWave};
    2.         WavesCollection collection = new WavesCollection();
    3.         collection.waves = new Wave[10];
    4.         wavesArray.CopyTo(collection.waves, 0);
    5.         StreamWriter sw = File.CreateText(WritePath);
    6.         string json = JsonUtility.ToJson(collection);
    7.         sw.WriteLine(json);
    8.         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
    Code (JavaScript):
    1. {"waves":[{"instanceID":-99992},{"instanceID":-99992},{"instanceID":-99992},{"instanceID":0},{"instanceID":0},{"instanceID":0},{"instanceID":0},{"instanceID":0},{"instanceID":0},{"instanceID":0}]}
    2.  
    Could anyone give me a few directions on what I'm doing wrong?
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    You're still trying to serialize a MonoBehaviour instance directly. Wrapping it in another class won't do anything. You need a "WaveData" class that holds the values in Wave that you care about. Then you can serialize a collection of WaveData.
     
  3. StanMihai72

    StanMihai72

    Joined:
    Apr 8, 2015
    Posts:
    6
    That's not the case as I can serialize Monobehaviours directly without issue. The problem is that I can't serialize arrays of objects with Unity's JsonUtility.