Crave For Games


The text below is one of the notes from the StoneDrop development log. If you want a list of only technical articles you can go to the Articles page.
Serialization (Unity3d, C#)

All project data (except for the localization) are stored as serialized objects, which contain all the information about a particular aspect of the game (player state, game progress, levels of a singleplayer, levels and game-boards created in editor, etc.).

 

For serialization the BinaryFormatter (goo.gl/nv8bAB[1]) is used. Such approach allows us to use considerably less memory (comparing, for instance, with the serialization in Json-string format goo.gl/4xHiQo[2] or XML-file format via XmlSerializer) and it is relatively fast (In C#, there are faster ways goo.gl/0NPxf8[3] but they require third-party libraries).

 

There are two ways to make a class serializable: either to add an attribute [Serializable] (goo.gl/KuqF7c[4]) or to implement an interface ISerializable. The first option is convenient because you don't have to write any additional code (the only thing you need is to take into account that all fields of the class have to be serializable or you need to mark non-serialized fields by attribute [NonSerialized]). The second option is used for more detailed serialization process: you need to implement two methods where you have to describe explicitly which data and how are serialized and deserialized.

 

Almost for all my classes I use an attribute [Serializable] but for some classes (containing fields of Dictionary type) I have to use an interface ISerializable and implement the method

public void GetObjectData(SerializationInfo info, StreamingContext context)

and a constructor for deserialization

protected ClassName(SerializationInfo info, StreamingContext context).

The reason is the slow speed of dictionaries serialization (goo.gl/UAQEo1[5]), thus, fields of Dictionary type are marked as [NonSerialized] and during the serialization they are converted into arrays of keys and values (figure 1).

151220_dict_example.png

Figure 1. Example of a class with Dictionary

 

A particular static class Serializer is responsible for the serialization and deserialization (figure 2). It is a class that convenient to have because you can quickly adjust the serialization here (for example add an encryption).

151220_serializer.png

Figure 2. Example of the Serializer class with ability to add encription to all serialized files in the project

 

Link 1: goo.gl/nv8bAB

Link 2: goo.gl/4xHiQo

Link 3: goo.gl/0NPxf8

Link 4: goo.gl/KuqF7c

Link 5: goo.gl/UAQEo1

This article in social networks: