Unity save everything (snapshot)

2019-02-25 12:29发布

I'm trying to save everything whilst running my program. I want to save every Gameobject with their scripts and variables. I know that it's possible to serialize everything and save it to an XML (and other ways/formats like JSON). This would require alot of work and time. The program may change alot in the future so the upkeep of maintaining this approach would be very time consuming. so I would prefer to use a different approach.

In unity it's possible to save and load a scene and I was hoping if someone knows something similair. I know it's possible to save Scenes during runtime like this article: https://docs.unity3d.com/550/Documentation/ScriptReference/EditorApplication.SaveScene.html

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

Hopefully someone direct me in a direction which is not very time consuming to implement.

Any help is appreciated!

1条回答
forever°为你锁心
2楼-- · 2019-02-25 13:09

This is where MVC comes in really handy.

It's kind of advanced, but I hope you'll find it useful.

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 the state in the model. The views represent the state in a visual way.

As an example, 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 of it:

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 Model to JSON:

string json = JsonUtility.ToJson(model);

And deserialize JSON to Model:

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

Having this state, you can iterate through the needed information and create GameObjects for them, so that you're able to represent the information in a visual way.

查看更多
登录 后发表回答