liveBook · Manning

Serialization

As explained in High Performance Unity Game Development

Serialization is the encoding of in-memory data into a storable or transferable representation.

Serialization encodes data as a stream of bytes; deserialization reads that stream back. Binary storage gives direct control over representation and can reduce save-file size, but the reader must consume fields in the same order they were written. section 7.1.1

Saving enemy data

A Unity save can use a FileStream with BinaryWriter to write an enemy count, then each enemy’s position. BinaryReader reads the values back in the same order. A short can store counts up to 32,767 using fewer bytes, but smaller types may require extra CPU work. section 7.1.1

Listing 7.5 Writing data in binary
string fileName = Application.persistentDataPath + "/DODSurvivor/gamedata.dat";
using (FileStream fs = File.Create(fileName))
using (BinaryWriter bw = new BinaryWriter(fs))
{
    int numEnemies = gameData.EnemyPosition.Length;
    bw.Write(numEnemies);
}

See the Unity-oriented BinaryWriter example for writing an enemy count to a save file. section 7.1.1

How High Performance Unity Game Development covers it

How deep it goes
Defines byte-stream encoding and ordering, then demonstrates reading and writing; it does not develop a complete save system.
Examples
Uses a game-data save with an enemy count and enemy positions as binary values.
What it assumes
Explains byte-stream storage for readers unfamiliar with binary representation.
What you can do after
Apply serialization with BinaryWriter and deserialization with BinaryReader to store and retrieve typed game data.
How it connects
Connects serialization with deserialization, binary files, FileStream, BinaryWriter, and BinaryReader.

Also explained in

Compare how 27 books explain serialization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of High Performance Unity Game Development. The section links point to the parts of the book it draws on.