Unity save everything (snapshot)

后端 未结 1 507
粉色の甜心
粉色の甜心 2021-01-14 14:44

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 everythin

相关标签:
1条回答
  • 2021-01-14 15:21

    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.

    0 讨论(0)
提交回复
热议问题