1

What is the appropriate way to cycle through all active gameobjects, and save instance data every ten seconds?

Ideally I would like to create a a singular JSON file that houses all gameobject data, similar to the following:

            {
                "Instance ID" : " xxxxxx"
                "Time" : 10
                "Attributes" : [
                    { "Position" : "(xx,xx) },
                    { "Speed" : "xxx" },
                    { "Color" : "xxx" },
                ]
                "Instance ID" : " xxxxxx"
                "Time" : 20
                "Attributes" : [
                    { "Position" : "(xx,xx) },
                    { "Speed" : "xxx" },
                    { "Color" : "xxx" },
                ]
                ...
            }

Currently I can save a singular gameobject's data every 10 seconds. However, the inclusion of a secondary gameobject merely overwrites the original JSON file.

  • Possible duplicate of [Serialize and Deserialize Json and Json Array in Unity](https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity) – derHugo Dec 02 '19 at 07:04

1 Answers1

1

This Link covers JsonUtility, the JSON serialization from unity documentation.

Here is a rough outline of your example json:

[Serializable]
public class CustomObject
{
    public int instanceID;
    public float time;
    public Vector2 position;
    public float speed;
    public string color;
}
CustomObject myObject = new CustomObject();
myObject.instanceID = 1;
myObject.time = 10.0;
myObject.position = new Vector2(0.0f, 0.0f);
myObject.speed = 23;
myObject.color = 'red';

string jsonObject = JsonUtility.ToJson(myObject);

then later when you want to put it into an object again:

anotherObject = JsonUtility.FromJson<CustomObject>(jsonObject);

I haven't tested it, I have no idea if it works, but it should be enough to point you in the right direction.

KindaSorta
  • 76
  • 4