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
