Subscribe to our newsletter
This blog will cover the basics of serialization and the three most common methods of serialization in Unity: JSON, XML and Binary.
Serialization is the process of converting an object into a form that can stored or transported easily.
Objects are instances of classes and they are converted to a stream of bytes. This stream can then be stored as a file, saved onto a database or sent over internet to a web service.
The reverse of this process, converting a stream which can be a file or a string into an object is called deserialization.
It's easier to understand it using a simple example. In this example, the player details need to be saved, so that when the players replays the game, the details are already available to them. They don't need to provide it on every game session.
When the player inputs his details into PlayerData object the state of the object is serialized and stored as a file. In the next play session the saved file is deserialized to recreate or clone the same state of our object. JSON and XML are two common standard serialization formats and both of them are shown in the image below. These standards have their own pros and cons and will be discussed later.
Serialization is used extensively by the unity game engine itself for things like saving data of MonoBehaviours and scriptable objects, editor scripting, prefabs, instantiation, saving and loading your scenes etc. This post will only focus on the use of serialization that you may encounter in a game.
Uses of Serialization
JSON is the most preferred data exchange format for the internet. Web browsers and servers continuously use JSON to communicat between each other.
JSON Serialization and Deserialization
XML Serialization and Deserialization
JSON vs XML
Binary serialization converts and object into a binary format, which is a byte stream.
Binary Serialization and Deserialization