Tag Archives: exit

Saving and Loading Level Data in Unity

This describes a method of persisting data in Unity. For example, saving and loading the current game level.

The first thing that you will need is to create a helper class to read and write the data that you need:

        public static void SaveGameState()
        {
            XmlDocument xml = new XmlDocument();
            var el = xml.CreateElement("PlayerStatus");
            el.SetAttribute("CurrentLevel", Application.loadedLevel.ToString());
            xml.AppendChild(el);
            xml.Save("data.xml");
        }

        public static void LoadGameState()
        {
            XmlDocument xml = new XmlDocument();
            xml.Load("data.xml");
            var el = xml.GetElementsByTagName("PlayerStatus")[0];
            string currentLevel = el.Attributes["CurrentLevel"].Value;
            int loadLevel = 0;
            if (!string.IsNullOrEmpty(currentLevel))
            {
                loadLevel = int.Parse(currentLevel);
                if (Application.loadedLevel != loadLevel)
                    Application.LoadLevel(loadLevel);
            }
        }

The next stage is to plug this into Unity. I put the following in a Master Script (which is essentially just a script associated with an empty game object).

    void OnApplicationQuit()
    {
        GameState.SaveGameState();       
    }

    void Start()
    {
        GameState.LoadGameState();
    }

I’ve seen plenty of articles on using serialisation for this, and that would obviously have the same effect, but this is another option.