- Home /
Question by
wurstbrotrest · Feb 21, 2016 at 09:59 AM ·
c#arrayjsonserializable
Constructing object array with JsonUtility
Using Unity 5.3 and the new JsonUtility I need to create a string like this:
{"highscore":[{"name":"BadBoy","scores":8828},{"name":"MadMax","scores":4711}]}
However I get only this string (Note: MadMax twice, but no BadBoy):
{"highscore":[{"name":"MadMax","scores":4711},{"name":"MadMax","scores":4711}]}
What´s wrong with my code (see below)? Can you help me how to fix it? I attached this script to the Main Camera in Unity3D.
using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;
public class JSONio03 : MonoBehaviour {
public MainObjectData mainObject;
public InnerObjectData innerObject;
List <InnerObjectData> objectList = new List<InnerObjectData> ();
public InnerObjectData createSubObject(string name, int scores){
innerObject.name = name;
innerObject.scores = scores;
return innerObject;
}
void Start () {
objectList.Add (createSubObject ("BadBoy", 8828));
objectList.Add (createSubObject ("MadMax", 4711));
mainObject.highscore = objectList.ToArray();
string generatedJsonString = JsonUtility.ToJson(mainObject);
Debug.Log ("generatedJsonString: " + generatedJsonString);
}
}
[Serializable]
public class MainObjectData {
public InnerObjectData [] highscore;
}
[Serializable]
public class InnerObjectData {
public string name;
public int scores;
}
Comment
Best Answer
Answer by flashframe · Feb 21, 2016 at 02:40 PM
It's because your list is holding two references to the same instance of "innerobjectdata".
You should instantiate a new innerobjectdata object in your "createsubobject" method each time you want to add to your list.
public InnerObjectData createSubObject(string name, int scores){
InnerObjectData myInnerObject = new InnerObjectData();
myInnerObject.name = name;
myInnerObject.scores = scores;
return myInnerObject;
}
Ha! Instantiating, that´s the clue! Thanks so much. It´s working – great!