I wrote a short code to Save and Load the highscore of my game, but it doesn’t do what its supposed to. It throws this exception:
SerializationException: serializationStream supports seeking, but its length is 0
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.NoCheckDeserialize (System.IO.Stream serializationStream, System.Runtime.Remoting.Messaging.HeaderHandler handler) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.cs:155)
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize (System.IO.Stream serializationStream) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.cs:136)
GameController.Load () (at Assets/scripts/GameController.cs:299)
GameController.Awake () (at Assets/scripts/GameController.cs:82)
What am i doing wrong? Probably something really obvious, but i just can’t find it.
Here is the code:
[System.Serializable]
public class Data
{
public int highscore;
public string highscoreName;
}
public void Save()
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream file = File.Open(Application.dataPath + "/highscore.dat", FileMode.OpenOrCreate);
Data.highscore = GetComponent<GameController>().Data.highscore;
Data.highscoreName = GetComponent<GameController>().Data.highscoreName;
formatter.Serialize(file, Data);
file.Close();
}
public void Load()
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream file = File.Open(Application.dataPath + "/highscore.dat", FileMode.OpenOrCreate);
Data Data = (Data)formatter.Deserialize(file);
GetComponent<GameController>().Data.highscore = Data.highscore;
GetComponent<GameController>().Data.highscoreName = Data.highscoreName;
file.Close();
}