liveBook · Manning

BinaryReader

As explained in High Performance Unity Game Development

BinaryReader is a .NET class that reads primitive types in binary from a stream.

For a game save stored as bytes, BinaryReader reads values back from a stream. Pair it with a FileStream and read each value using the type that matches what was written; BinaryFormatter is not recommended because of security vulnerabilities. section 7.1.1

For a save file containing enemy data:

  • Read an integer enemy count with ReadInt32, or read a short count with ReadInt16 if the file stores it as a short. section 7.1.1
  • Read floating-point values with ReadSingle; restore each Vector2 position by reading its x and y components. section 7.1.1
Listing 7.6 Reading data in binary
string fileName = Application.persistentDataPath + "/DODSurvivor/gamedata.dat";
if (File.Exists(fileName))
{
    using (FileStream stream = File.Open(fileName, FileMode.Open))
    using (BinaryReader br = new BinaryReader(stream))
    {
        int numEnemies = br.ReadInt32();
    }
}

Example setup opens an existing save file and reads its enemy count through a BinaryReader. section 7.1.1

How High Performance Unity Game Development covers it

How deep it goes
Demonstrates typed reads for integers, shorts, floats, and Vector2 components, without detailing broader file-format handling.
Examples
Reads an enemy count and restores enemy positions by reading each Vector2 coordinate.
What you can do after
Apply it via BinaryReader to read typed values from a saved-data stream.
How it connects
Connects binary deserialization with serialization, BinaryWriter, FileStream, and primitive types.

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.