Saving Data

Let’s suppose you’re making a “complete” game. You want a title screen and everything. Your user can select the number of players or a difficulty setting, etc, and then… how do you pass the information on to the next scene? Or more importantly (and somewhat tricker) how can you save a game session and load it again later? Read along and I will show some of the options I like.

Static Persistance

To persist data from one scene to another can be as simple as saving data to a static variable. To demonstrate, we will need a bit of setup. Create two scenes, one called “Title” and one called “Game”. From the menu bar choose “File->Build Settings” and in the dialog you will need to use the “Add Current” button or drag and drop both scenes from the Project pane into the “Scenes In Build” list.

The following Data Manager class is a static class with a static variable, so it doesn’t need to be added to your scene, it will just “work” automatically. I make use of something called an “enum” which I haven’t talked about before. For now, you can think of an enum as an integer (because it can be cast to or from an integer – although it is actually its own ‘type’) where each entry is named to make your code more readable. “Easy” is like the integer value of ‘0’ and it counts up from there.

using UnityEngine;
using System.Collections;

public enum Difficulties
{
	Easy,
	Medium,
	Hard,
	Count
}

public static class DataManager
{
	public static Difficulties difficulty;
}

Add the following “TitleController” script as a component to the camera in the “Title” scene. This script is very simple – I used the legacy GUI to reduce setup time even further. All this script does is show buttons for each difficulty option, and one to begin playing the game. Whenever you select one of the buttons, a difficulty setting is set to a static variable in the DataManager class.

using UnityEngine;
using System.Collections;

public class TitleController : MonoBehaviour 
{
	void OnGUI ()
	{
		int yPos = 10;
		GUI.Label(new Rect(10, yPos, 200, 30), "Choose Difficulty");

		for (int i = 0; i < (int)Difficulties.Count; ++i)
		{
			yPos += 40;
			Difficulties type = (Difficulties)i;
			if (DataManager.difficulty == type)
				GUI.Label(new Rect(10, yPos, 200, 30), type.ToString());
			else if (GUI.Button(new Rect(10, yPos, 100, 30), type.ToString()))
				DataManager.difficulty = type;
		}

		yPos += 40;
		if (GUI.Button(new Rect(10, yPos, 100, 30), "Play"))
			Application.LoadLevel("Game");
	}
}

Add the following “GameController” script as a component to the camera in the “Game” scene. This script is also very simple. This time all I do is show which difficulty had been selected in the Title scene, and provide an option to Quit back to that scene.

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour 
{
	void OnGUI ()
	{
		GUI.Label(new Rect(10, 10, 200, 30), DataManager.difficulty.ToString());
		if (GUI.Button(new Rect(10, 50, 100, 30), "Quit"))
			Application.LoadLevel("Title");
	}
}

With the Title scene open, press Play and note that the selection you make on the first screen is saved and is still available in the next scene. This works because static variables never go out of scope for as long as the program is running.

Singleton Pattern

Although a static class worked fine for the previous sample, it doesn’t offer as many architectural options as an object would (namely inheritance and polymorphism). A singleton is a slightly different variation, where by design you still only want a single instance of a class to ever exist, but you can have more control over the creation and lifespan of the object, can use subclasses, etc.

public class DataManager
{
	public static readonly DataManager instance = new DataManager();
	private DataManager() {}

	public Difficulties difficulty;
}

Here I have modified the DataManager class so that it is no longer static. I create a static readonly instance of the class (so that no other class can destroy or reassign it) and make the constructor private (so no other class can instantiate another object). This forces the singleton pattern to be used as I intended.

Reading and writing the difficulty setting would now need to be routed through the singleton instance. The following line shows an example of writing the value:

DataManager.instance.difficulty = type;

Unity “Singleton”

Sometimes you may find it convenient to use a MonoBehaviour based class for your persistence (in case you want to take advantage of Coroutines, etc.) In that case you can make GameObjects “survive” a scene change by using the method “DontDestroyOnLoad”. Note that this is also a handy way to make music play between scene changes.

public class DataManager : MonoBehaviour
{
	public static DataManager instance
	{
		get
		{
			if (_instance == null)
			{
				GameObject obj = new GameObject("Data Manager");
				_instance = obj.AddComponent<DataManager>();
				DontDestroyOnLoad(obj);
			}
			return _instance;
		}
	}
	static DataManager _instance;

	public Difficulties difficulty;
}

This version of the DataManager inherits from MonoBehaviour. The “Singleton” is created by something called “Lazy Loading” which means that as soon as any script calls the “instance” property, the class will look at its “getter” and determine whether or not it has created one. If not, it will create a new GameObject, assign the correct component, and make sure that the GameObject is marked properly so it won’t be destroyed when changing scenes.

This version is not as “safe” as the previous version, because there are ways that other scripts could cause your script’s GameObject to be destroyed, and even though your script itself would “survive” due to the static reference, the comparison to null will still return true because the equals operator is overridden by Unity (to take into account the GameObject), therefore another GameObject/Singleton would be created.

Furthermore, nothing stops another script from adding additional copies of this component to other GameObjects, although because I provided no setter, only one component at a time will ever be recognized as the main instance.

Player Prefs

All of the examples so far are good ways of taking data from one scene to another, however not a single one of them can persist data across multiple play sessions. In order to accomplish this task, you need to save data to “disk” in one way or another. Unity provides a convenient solution without even needing to understand how to create, read and write to files. This solution is called PlayerPrefs – see the docs here http://docs.unity3d.com/ScriptReference/PlayerPrefs.html

You can think of the PlayerPrefs as a Dictionary which only knows how to work with a “string” for the key and either an “int”, “float”, or “string” for the value. Unlike a generic dictionary, you can mix and match any combination of those values.

Here are some use cases:

// Store an integer value
PlayerPrefs.SetInt("Difficulty", 0);

// Retrieve an integer value (if it exists, or use a default of '0' otherwise)
DataManager.instance.difficulty = (Difficulties)PlayerPrefs.GetInt("Difficulty", 0);

Serialization

I mentioned serialization once early on – Unity utilizes serialization to store values of your components while in the editor. Unfortunately, a lot of the convenient options you might like to make use of such as a Binary or XML Serializer would require you to be able to use a Constructor – not an option with MonoBehaviour. Furthermore, object hierarchy, object references, and a desire to persist values in native Unity components all greatly complicate this process.

The method I prefer is manual serialization into JSON strings. Although it requires a bit more setup than some of the other routes, I feel that I have a lot more options and maintain full control over the process. I also don’t have to worry about “versioning” my data. I can remove data, add data, change data types, etc and it won’t cause the serializer to crash, because I can control the process of what and how I persist data. For example, I can check for the presence of keys and try casting data types where necessary. Additionally, because I am serializing to a JSON string I can very easily persist the result to PlayerPrefs, submit it to a server, or write it to a local file as desired.

I decided not to re-invent the wheel this time around, and used a public script for the JSON serialization instead. Grab a copy here, https://gist.github.com/darktable/1411710 and add it to your project.

Create a new scene called “Demo”. Create a Cube (from the menu bar choose “GameObject->3D Object->Cube”) and then create and attach the following “Monster” script (because aren’t monsters more fun to work with?)

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class Monster : MonoBehaviour
{
	public int HP;
	
	public virtual Dictionary<string, object> Save ()
	{
		Dictionary<string, object> data = new Dictionary<string, object>();
		data.Add("HP", HP);
		data.Add("X", transform.localPosition.x);
		data.Add("Y", transform.localPosition.y);
		data.Add("Z", transform.localPosition.z);
		data.Add("Prefab", gameObject.name);
		return data;
	}
	
	public virtual void Load (Dictionary<string, object> data)
	{
		HP = Convert.ToInt32( data["HP"] );
		float x = Convert.ToSingle( data["X"] );
		float y = Convert.ToSingle( data["Y"] );
		float z = Convert.ToSingle( data["Z"] );
		transform.localPosition = new Vector3(x, y, z);
	}
}

This script has a single field for “HP” – hit points. It doesn’t really do anything, but I want to show that we will be able to save both a local variable as well as values from the transform component. The Save and Load methods serve (hopefully) obvious purposes. They wrap the object’s data into a generic dictionary which the MiniJSON script knows how to serialize into a JSON string.

Create and attach the following script to the camera, and then connect the Cube as the reference for the monster field:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using MiniJSON;

public class Demo : MonoBehaviour 
{	
	public Monster monster;

	void Start ()
	{
		Load ();
	}

	void OnGUI ()
	{
		if (GUI.Button(new Rect(10, 10, 100, 30), "Randomize"))
			Randomize ();

		if (GUI.Button(new Rect(10, 50, 100, 30), "Save"))
			Save ();
		
		if (GUI.Button(new Rect(10, 90, 100, 30), "Load"))
			Load ();
	}

	void Randomize ()
	{
		monster.HP = UnityEngine.Random.Range(10, 100);
		float x = UnityEngine.Random.Range(-10f, 10f);
		float y = UnityEngine.Random.Range(-10f, 10f);
		float z = UnityEngine.Random.Range(-10f, 10f);
		monster.transform.localPosition = new Vector3(x, y, z);
	}
	
	void Save ()
	{
		string json = Json.Serialize( monster.Save() );
		Debug.Log(json);
		PlayerPrefs.SetString( "Monster", json );
	}
	
	void Load ()
	{
		string json = PlayerPrefs.GetString( "Monster", string.Empty );
		if (!string.IsNullOrEmpty(json))
		{
			var dict = Json.Deserialize(json) as Dictionary<string,object>;
			monster.Load(dict);
		}
	}
}

This script uses the legacy GUI like before, to either move the monster around, Save its data, or Load its data. I use the MiniJSON script we downloaded for serialization, and then save the result to PlayerPrefs for persistence sake.

Run the scene. Click Randomize to your heart’s content. At some point click Save and then randomize a few more times. Now click Load and see that the monster is moved back to the location it was in when you clicked Save. Stop the scene and then run it again. The monster should still be in the place where you saved it!

Although you technically know everything you need at this point, a few more issues may not be obvious. For example, what if you have a list of objects you want to save? Do you need to create a new player pref for each one? What if you want to use polymorphism or dynamically create and persist objects? These are each very normal architectural requirements so let’s handle them next.

For our first step, we will need to modify the Monster script so that the Save and Load methods are marked as “virtual”. This way we don’t have to completely re-write the Persistence code in every sub-class, instead, we only have to override the base method and append whatever new data the sub class provides.

I decided to create three subclasses of Monster: “BlueMonster”, “RedMonster”, and “GreenMonster” – I know, very imaginative class names right? The blue monster is listed below:

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class BlueMonster : Monster 
{
	public int water;

	void Awake ()
	{
		water = UnityEngine.Random.Range(10, 100);
	}

	public override Dictionary<string, object> Save ()
	{
		Dictionary<string, object> data = base.Save ();
		data.Add("Water", water);
		return data;
	}

	public override void Load (Dictionary<string, object> data)
	{
		base.Load (data);
		water = Convert.ToInt32( data["Water"] );
	}
}

The red and green monsters have identical implementations, except that I named the local variable “fire” and “earth” in the red and green monster scripts respectively. The goal here is to illustrate that you can’t use the same serialization across all three because they have “different” data sets. However, because they share a common base class, I can treat them all the same and will be able to save and load them without concern of their differences.

To help emphasize the differences between our monsters, Create three different prefabs in your project, one for each monster. You might make one with a sphere and one with a cube, but at a minimum color them all based on their name to help show that there is in fact a difference. Make sure and assign the specific sub class script to each type of monster and not the base class version of itself.

Now we need to modify the Demo script for our new functionality:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using MiniJSON;

public class Demo : MonoBehaviour 
{
	[SerializeField] GameObject[] prefabs;
	Dictionary<string, GameObject> mapping = new Dictionary<string, GameObject>();
	List<Monster> monsters = new List<Monster>();

	void Start ()
	{
		for (int i = 0; i < prefabs.Length; ++i)
			mapping.Add(prefabs[i].name, prefabs[i]);
		Load ();
	}
	
	void OnGUI ()
	{
		if (GUI.Button(new Rect(10, 10, 100, 30), "Add"))
			AddRandom ();
		
		if (GUI.Button(new Rect(10, 50, 100, 30), "Save"))
			Save ();
		
		if (GUI.Button(new Rect(10, 90, 100, 30), "Load"))
			Load ();
	}
	
	void Randomize (Monster monster)
	{
		monster.HP = UnityEngine.Random.Range(10, 100);
		float x = UnityEngine.Random.Range(-10f, 10f);
		float y = UnityEngine.Random.Range(-10f, 10f);
		float z = UnityEngine.Random.Range(-10f, 10f);
		monster.transform.localPosition = new Vector3(x, y, z);
	}
	
	void AddRandom ()
	{
		GameObject prefab = prefabs[ UnityEngine.Random.Range(0, prefabs.Length) ];
		Monster monster = Add(prefab);
		Randomize(monster);
	}
	
	Monster Add (GameObject prefab)
	{
		GameObject instance = Instantiate(prefab) as GameObject;
		Monster monster = instance.GetComponent<Monster>();
		monster.name = prefab.name;
		monsters.Add(monster);
		return monster;
	}
	
	void Save ()
	{
		var monsterData = new List<Dictionary<string, object>>( monsters.Count );
		for (int i = 0; i < monsters.Count; ++i)
			monsterData.Add( monsters[i].Save() );
		
		string json = Json.Serialize(monsterData);
		Debug.Log(json);
		PlayerPrefs.SetString( "Monsters", json );
	}
	
	void Load ()
	{
		Clear();
		string json = PlayerPrefs.GetString( "Monsters", string.Empty );
		if (!string.IsNullOrEmpty(json))
		{
			var monsterData = Json.Deserialize(json) as List<object>;
			for (int i = 0; i < monsterData.Count; ++i)
			{
				Dictionary<string, object> data = monsterData[i] as Dictionary<string, object>;
				string prefab = (string)(data["Prefab"]);
				Monster monster = Add ( mapping[prefab] );
				monster.Load( data );
			}
		}
	}
	
	void Clear ()
	{
		for (int i = monsters.Count - 1; i >= 0; --i)
			Destroy(monsters[i].gameObject);
		monsters.Clear();
	}
}

In this version, I no longer need the reference to the single Monster object. Since we are creating from a variety of monster types dynamically, I need references to the prefabs which we can Instantiate (line 8). These could have been obtained through Resources.Load, but this version is acceptable for now. Don’t forget to assign them in the editor.

Next I created a dictionary to map from a prefab name to the prefab itself (line 9) – that setup occurs in the Start method (lines 14-15). This step may seem a bit redundant, but I find the code a bit more readable (not to mention more efficient) than code which needs to search the array for a match (lots of string comparisons = SLOW).

I only slightly modified the OnGUI code – I replaced the button which moved the original Monster around, with a button to create new dynamic monsters which will already be moved around.

The “Randomize” method now requires a Monster parameter to be passed to it, since we want to be able to move any of our monsters with the same code.

The “AddRandom” method is new and picks one of the prefabs at random to create. It then makes sure the newly created monster is Randomized with the previously mentioned method.

The “Add” method takes a prefab as a parameter, from which it will instantiate a new monster. The monster script stores a reference to the name of the prefab which was used, so that we can use the same prefab again later when we need to actually persist the object. After instantiating the monster, we get a reference to the monster script (note that the GetComponent will work because our subclass versions of Monster are still Monster components) and add the component to a list so we can easily keep track of and manage everything we have created.

The Save method is similar to the previous version, but now we are creating a list of dictionary objects, instead of just a single dictionary. Our JSON serializer can serialize the whole thing as one string, so we can easily stick it in a PlayerPref as we did before. Note that I used a pluralized key this time for clarity.

The Load method changed a bit more, but not too bad. First I destroy any existing monsters before creating new ones according to the Save data. Note that this is easier than a Queue system, but a queue of reusable objects is more ideal in production code. The other big difference (besides working with a list of dictionaries) is that I get a reference to the prefab name within each entry and Instantiate a new object accordingly. Then I load the corresponding data on the spawned object. This is important because a Red Monster would fail to load correctly if it were passed a Blue Monster’s data and vice-versa.

Feel free to run the scene and give everything a try. Add a bunch of monsters, save the data (note that I also log a version of the JSON output to the console in case you want to inspect it) and then try stopping and starting a new session. All of your dynamically created monsters load back just fine!

Files

If you are saving lots of data, or if it makes sense to break your data up into smaller chunks which can be loaded at different times, then it may make sense to write to files instead of putting too much into PlayerPrefs.

Using the same example from before you can modify just the Save and Load methods as follows:

void Save ()
{
	var monsterData = new List<Dictionary<string, object>>( monsters.Count );
	for (int i = 0; i < monsters.Count; ++i)
		monsterData.Add( monsters[i].Save() );
	
	string json = Json.Serialize(monsterData);
	string filePath = Application.persistentDataPath + "/Monsters.txt";
	File.WriteAllText(filePath, json);
}

void Load ()
{
	Clear();
	string filePath = Application.persistentDataPath + "/Monsters.txt";
	if (File.Exists(filePath))
	{
		string json = File.ReadAllText(filePath);
		var monsterData = Json.Deserialize(json) as List<object>;
		for (int i = 0; i < monsterData.Count; ++i)
		{
			Dictionary<string, object> data = monsterData[i] as Dictionary<string, object>;
			string prefab = (string)(data["Prefab"]);
			Monster monster = Add ( mapping[prefab] );
			monster.Load( data );
		}
	}
}

Summary

In this lesson we covered a few methods of data persistence. First we covered temporary persistence through static classes, the Singleton design pattern, and Unity GameObjects which can survive scene changes. Then we explored how data can be persisted even across multiple play sessions via PlayerPrefs, JSON serialization and writing data to files. We even got a bit fancy by persisting a list of dynamically created polymorphic objects.

4 thoughts on “Saving Data

  1. Hey Jonathan,
    I’ve been following this series of great tutorials from the very first page.
    Unfortunately, it appears I’m encountering an error and I don’t really know what’s wrong.

    On the last part of ‘Serialization’, you need to modify the Demo script to add new functionalities, regarding the prefab monsters.

    I checked, double-checked and eventually gave up and copy-pasted your code but I get the error :

    line 51 – monster.prefab = prefab.name; ‘Monster’ does not contain definition for ‘prefab’ and no extension method accepting a first argument of type ‘Monster’ could be found.

    If you have any idea regarding this error, I would be very thankful. 🙂

    1. My apologies, the post was messed up somehow, and you are correct that it wouldn’t compile. I have updated it, and it should be fine now. The line that was giving you a problem was supposed to be assigning the name of the prefab to the name of the instantiated game object. The Monster script should then add its own name to the dictionary in the “save” method so it could be loaded again later. I also noticed that the Monster script need the save and load methods to be virtual so that the subclasses could override them.

      Take another look at both the Monster and Demo scripts and hopefully everything will make more sense now.

      Also, I went ahead and made a working project sample just in case: https://drive.google.com/file/d/0B2xa1STfdTsYbFhZVUR6cGxmemM/view?usp=sharing

  2. Hey Jon,

    Your project works great (obviously) and the Add() function works pretty well now on mine.
    I get a nasty error when Saving though.

    KeyNotFoundException: The given key was not present in the dictionary.
    System.Collections.Generic.Dictionary`2[System.String,System.Object].get_Item (System.String key) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150)
    Demo.Load () (at Assets/Scripts/tutorial/Demo.cs:77)
    Demo.Start () (at Assets/Scripts/tutorial/Demo.cs:16)

    I think I understand the reasoning behind the saving process thanks to your tutorial/completed process anyway. So thanks 🙂

    1. My pleasure, I am glad you were able to grasp the idea now. Sometimes while developing you may have already saved an incompatible version of data to the Player prefs and will need to wipe it and start over. You can accomplish this with PlayerPrefs.DeleteAll(). Sometimes I make an editor script specifically for this purpose.

Leave a Reply

Your email address will not be published. Required fields are marked *