Game Development Reference
In-Depth Information
Serializing your data
To store any kind of complicated data or structure, you need to serialize it into a concaten-
ated format. The result can then be stored in PlayerPref as mentioned previously or
saved on a disk or the Web.
There are several types of serializers you can use, including the following:
Binary serialization : This is binary-formatted output and is non-human readable
XML serialization : This is the basic text output formatted into XML and is hu-
man readable
JSON serialization : This is a compressed standalone output in XML format; it is
human readable and allows you to have a manual implementation
Custom serialization : This is DIY and is used to build your own serialized out-
put
Each serializer has performance or security gains. There isn't a one size fits all; just
choose the serializer that fits your purposes.
For our example, we will enhance our game to save our player's state. First, we will create
a helper function to do the serialization for us, so create a new script called Serializa-
tionHelper in Assets\Scripts\Classes and replace its contents with the fol-
lowing code:
using System.IO;
using System.Xml.Serialization;
public class SerilizerHelper {
}
Now, in this script, we will add two functions: one to serialize our player (pack it up) and
one to deserialize it (unpack it). The serialize function is as follows:
public static byte[] Serialise<T>(T input)
{
byte[] output = null;
//Create an XML formatter
var serializer = new XmlSerializer(typeof(T));
try
Search WWH ::




Custom Search