Serialization failed.

I used the following code to save and then load data. The save works well and the highScore ends up in savedGameData:

{
            savedGameData.highScore = gameController.GetComponent<GameController>().highScore;
}
{
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Create(Application.persistentDataPath + "/saveGame.sav");
            bf.Serialize(file, savedGameData);
            file.Close();
}

The load part does not because after deserialization, highScore is 0. I confirmed that it is also 0 in savedGameData when I attached the code to Unity.

if (File.Exists(Application.persistentDataPath + "/saveGame.sav"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/saveGame.sav", FileMode.Open);
            GameStats savedGameData = (GameStats)bf.Deserialize(file);
            file.Close();
        }

The code also includes:

    public GameStats GetSavedGameData()
    {
        return savedGameData;
    }

}
[System.Serializable]
public class GameStats 
{
    public float highScore;
}

What did I do wrong here?

Well, Are you actually sure about what value you saved? Can you share your “saveGame.sav” file?

Once again I highly recommend to not use the BinaryFormatter for such things. The generated file for such trivial data has huge overhead. Most who choose the BinaryFormatter just want a “non-readable” / not modifiable save. Both is no achieved that way. It’s a little bit harder but quite trivial. I highly recommend to just use a human readable format like JSON and if you want to make it non readable, just use a simple “scramble” / “unscramble” once you’re ready to ship your game. You could simply use base64 encoding which makes it equally difficult to read / modify. However a simple xor of the data with a fix key would be much more difficult to break than the BinaryFormatter. That way it would make debugging much easier since you can simply disable the obfuscation until you actually ship the game.

The BinaryFormatter uses a well known format (the MS remoting protocol). It’s in general not hard to read or modify. It’s also quite verbose. But the biggest issue is that it’s very strict and doesn’t allow any change in the structure of the saved data. So a new version where you changed some fields of your class would completely break older saves.

Regardless if you really want to stick to it you should first make sure what value you actually serialized. Again, if you can share a sample saveGame.sav file I can tell you what value is stored inside.