Unity save everything (snapshot)

做~自己de王妃 提交于 2019-12-01 06:25:35

问题


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:


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.



来源:https://stackoverflow.com/questions/43676534/unity-save-everything-snapshot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!