Serialization – Saving Objects as Files

Unity’s often used built in form of serialization are the PlayerPrefs. As Lars Kokemohr, the Head of Programming at the School4Games, points out in this Facebook post: The are a lot of drawbacks to saving data using Unity’s PlayerPrefs class. Furthermore he advises that

A cleaner way of doing it would be to create a new file in the path that is stored in Application.persistentDataPath. […] This […] could then be stored using Mono’s BinaryFormatter class.

So in this post I am going to show you how serialization allows you to do just that. The scripts I am using for that is a modified version of what can be found in this blogpost by Ryan Nielson.

Saving the State of an Object = Serialization

In object-oriented programming data is stored in objects, like a class or a struct. You could have a Highscore class for example that saves a player name (e.g. Kevin) and a highscore (e.g. 9001). When this highscore is saved as a file the highscore object (An instance of the Highscore class) and it’s state (i.e. the player name being Kevin and the highscore being 9001) a taken out of memory and converted into a format that can be saved. This process is known as serialization. The process of reading a file and reverting it into the original Highscore object with it’s original state is known as deserialization. C# allows for two basic kinds of serialization: XMLSerialization and binary serialization. XML serializes objects into human readable files. The xml serialized file of the Highscore class could be edited with a basic text editor, which means that everyone could easily change the highscore value with notepad. Binary serialization on the other hand results in a binary file which can not be read and manipulated easily by humans. For the purpose of a Highscore class binary serialization should be used. Another important difference is that xml files can be merged with version control software, whereas binary files can not. For a super deep comparision of the two kinds of serialization (as well as some others) you can read this post. If you want a quick comparision

Type / FeatureBinary SerializerXml Serializer
DespriptionSerializes and object in an internal binary format that the .NET Framework understands.
Serializes and object in universal XML format.
RequerimentsThe type needs to be marked with the [Serializable] atribute
Type must be public (public class person)

Must implement a parameterless constructor (in order to deserialize the object)

If you are serializing a non generic collection of items, you must pass the types that are stored in the collection as a parameter in the constructor of the XmlSerializer.
ProsThe output byte stream generated is compact

The serialization process is faster than using the other formatters.

Serializes public and private members (deep serialization)
Class doesn’t need to be decorated with [Serializable] attribute.

Developer has a deep control about how each field is going to be serialized by using attributes
ConsFormat not readable by other techonolgies (just .NET Framework)Only public members will be serialize! (shallow serialization)

Source

Saving and loading a simple Score value

The Basics of saving (in Xml)

Let’s start by saving a simple int variable named Score with xml and binary serialization. Im going to do this inside Unity so that I can save the files to the path defined in Unity’s Application.dataPath. Other than that this can be done completetly without Unity if you supply your own path instead of Application.dataPath.

using System.IO;
using System.Xml.Serialization;
using UnityEngine;

public class SimpleSaving : MonoBehaviour
{
int Score = 100;

public void Start()
{
using (var stream = new FileStream(Path.Combine(Application.dataPath, "test.xml"), FileMode.Create))
{
var formatter = new XmlSerializer(typeof(int));

formatter.Serialize(stream, Score);
}
}
}

The main 3 operations here are filestreams, XmlSerializers and the using notation. To create, open, read from and write to a file we need to establish a connection to that file. That connection is a Filestream, which is located in the System.IO namespace.

using System.IO;
using System.Xml.Serialization;
using UnityEngine;

public class SimpleSaving : MonoBehaviour
{
int Score = 100;

public void Start()
{
using (var stream = new FileStream(Path.Combine(Application.dataPath, "test.xml"), FileMode.Create))
{
var formatter = new XmlSerializer(typeof(int));

formatter.Serialize(stream, Score);
}
}
}

This particular filestream points a file in Application.dataPath that is named test.xml. FileMode.Create means if this file doesn’t already exist an empty file will be created and if it already exists it will be completely overwritten. Regardless of it’s existence or content, writing to this filestream will result in the same file output (and loss of the prior file).
Having established a connection to a file we need to serialize the score variable into a saveable format. To do that we use a Serializer.

using System.IO;
using System.Xml.Serialization;
using UnityEngine;

public class SimpleSaving : MonoBehaviour
{
int Score = 100;

public void Start()
{
using (var stream = new FileStream(Path.Combine(Application.dataPath, "test.xml"), FileMode.Create))
{
var formatter = new XmlSerializer(typeof(int));

formatter.Serialize(stream, Score);
}
}
}

In this cas the serializer we use is a XmlSerializer, which is located in the System.Xml.Serialization namespace. Furthermore we need to specify the type of the data we are going to serialize, in this case an integer, with typeof(int). Having done that we can serialize our Score variable to our file with formatter.Serialize(stream, Score).
After this we should dispose of our filestream, for example with stream.Dispose(), to release it from memory. Alternatively we can use the using(){} notation.

using (var stream = new FileStream(Path.Combine(Application.dataPath, "test.xml"), FileMode.Create))
{
var formatter = new XmlSerializer(typeof(int));

formatter.Serialize(stream, Score);
}

Because we declared the filestream inside the using statement c# will automatically dispose it, even if an error occurred.
The test.xml file we receive from this looks like this:

<?xml version="1.0" encoding="Windows-1252"?>
<int>100</int>

We could easily change the score variable from 100 to 100000 by editing it with a text editor.

The Basics of saving (in binary)

Now lets take a look at changes we have to make to save our Score in binary instead.

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

public class SimpleSaving : MonoBehaviour
{

int Score = 100;

public void Start()
{
using (var stream = new FileStream(Path.Combine(Application.dataPath, &quot;test.dat&quot;), FileMode.Create))
{
var formatter = new BinaryFormatter();

formatter.Serialize(stream, Score);
}
}
}

Instaed of using a XmlFormatter we use a BinaryFormatter, which is located in the System.Runtime.Serialization.Formatters.Binary namespace. Because a BinaryFormatter can serializes metadata like type infrmation, we don’t have to specifiy the type when we initiaize the formatter. We also change our file extension to .dat to indicate that is is a binary file that is not supposed to be in a human readable format. The test.dat file we receive from this looks like this:

After Serialization = A lot of nonsensical hex code.
Reading and editing this is much harder.

For saving a score this is a much more secure format.

Serializing a custom Class

From now we will only deal with binary serialization. For more information about xml serialization check out the official documentation as well as this post on udemy.

Now that we can save a primitive struct like an integer we are going to serialize our own custom classes. For this example we will create a serializable Highscore class.
Lets start by creating this class.

public class Highscore
{
public string Name;
public int Score;
public string Secret;
}

This is the Highscore class which has variables for a Name, a Score and a Secret. If we try to serialize it in it’s current form we would receive the following error: “SerializationException: Type Highscore is not marked as Serializable.” For a class to be serializable it must be marked with the [Serializable] attribute, that is located in the System namespace. Our Highscore class now looks like this:

using System;

[Serializable]
public class Highscore
{
public string Name;
public int Score;
public string Secret;
}

Now we can serialize our Highscore without problem. It is important to note that every member of this class must also be marked as serializable. C# primitives like ints and strings are marked with the serializable attribute by default. But some third party classes are not marked and therefore can’t be saved. For example one has to save Unity’s Vector3 as 3 separate float values.
We can also exclude certain fields from being serialized with the [NonSerialized] attribute.

using System;

[Serializable]
public class Highscore
{
public string Name;
public int Score;
[NonSerialized]
public string Secret;
}

Now after deserialization the Secret variable will be it’s default value, which is null. The default value for reference types is null, for numeric value types is 0 and for bools is false. You can find more information about default values in the official documentation.

Creating the basis for a Save System

Now that we know how to create our own serializable objects and how to serialize them, we can create a system to save, load and delete our data. We are going to start by making an interface for all our cutstom save classes.

using System;

[Serializable]
public abstract class DataCotainer
{
}

The DataContainer class is the base class of all classes that will be saved. It is marked with the [Serializable] attribute which means it can be serialized. Furthermore it is a abstract class, so it can’t be initialized with the new keyword and has to be inherited. This class is the interface (don’t confuse that with a c# interface) we will use to store all kinds of data / classes inherited from DataContainer.

using System;

[Serializable]
public class PlayerDataCotainer : DataCotainer
{
public string PlayerName = &quot;Ryan&quot;;

public int Score { get; set; }

[NonSerialized]
public string Secret = &quot;Nope&quot;;
}

This PlayerDataContainer is an actual class that will be saved. This class is used to store information about the player. It is inherited from DataContainer and is also marked with the [Serializable] attribute.