Unity saves everything (snapshot)

I am trying to save everything while I run my program. I want to keep each Gameobject with their scripts and variables. I know it is possible to serialize everything and store it in XML (and other ways / formats like JSON). It will take a lot of work and time. The program may change a lot in the future, so maintaining this approach will take a long time. so I would rather use a different approach.

In unity it is possible to save and load the scene and I was hoping someone knows something similar. I know it is possible to save scenes at runtime like this article: https://docs.unity3d.com/550/Documentation/ScriptReference/EditorApplication.SaveScene.html

However, and I may be wrong here, you still need to load variables from a file or something, so this approach is useless for me.

Hopefully someone will guide me in a direction that doesn't take long to implement.

Any help is appreciated!

+3


source to share


1 answer


This is where MVC comes in very handy.

This is advanced, but I hope you find it helpful.

You have all your state in one place, call it: Model

class.

You can serialize to and from JSON.

You create views by iterating through state in the model. Views represent state visually.

As an example, let's say you have this model class:

[Serializable]
public class Model {
    public string List<City> cities = new List<City>();
}

[Serializable]
public class City {
    public string name;
    public int population;
    public List<Person> people;
}

[Serializable]
public class Person {
    public string name;
    public int age;
}

      



Create a new instance:

Model model = new Model();
City c = new City();
c.name = "London";
c.population = 8674000;

Person p = new Person();
p.name = "Iggy"
p.age = 28;

c.people.Add(p);

model.cities.Add(c);

      

You can serialize the model to JSON:

string json = JsonUtility.ToJson(model);

      

And deserialize the JSON for the model:

model = JsonUtility.FromJson<Model>(json);

      

With this state in place, you can iterate over the information you need and create GameObjects for them so that you can present the information visually.

+2


source







All Articles