Deserializing problem at runtime, InvalidCastException

I was just messing around with serialization, when a strange error was popping up, only at runtime though. It says:

InvalidCastException: Cannot cast from source type to destination type. MyScript.Load ()

The adressed C# script (MyScript) contains this code:

	public static int highscore = 0;		//saved Highscore
	public static int collectedPoints = 0;	//Points collected on this account
	public static int lifetimeScore = 0;	//count of all points ever collected

	public static void Load()
	{
		if(File.Exists(Application.persistentDataPath + "/saveFiles.xyz"))
		{
			BinaryFormatter bf = new BinaryFormatter();
			FileStream file = File.Open(Application.persistentDataPath + "/saveFiles.xyz", FileMode.Open);
			SaveValues.highscore = (int)bf.Deserialize(file);
			SaveValues.collectedPoints = (int)bf.Deserialize(file);
			SaveValues.lifetimeScore = (int)bf.Deserialize(file);
			file.Close();
		}
	}

	public static void Save()
	{
		BinaryFormatter bf = new BinaryFormatter();
		FileStream file = File.Create (Application.persistentDataPath + "/saveFiles.xyz");
		bf.Serialize(file, SaveValues.highscore);
		bf.Serialize(file, SaveValues.collectedPoints);
		bf.Serialize (file, SaveValues.lifetimeScore);
		file.Close();
	}

	public static void Reset()
	{
		if (File.Exists (Application.persistentDataPath + "/saveFile.xyz"))
		{
			File.Delete (Application.persistentDataPath + "/saveFile.xyz");
			Application.LoadLevel(0);
		}
	}

SavedValues is the class containing these variables.
I think the error is pointing towards the “SavedValues.lifetimeScore”-line in the Load()-function.
What am i missing?

Thanks in advance.

Deserialize will deserialize an object graph from the given stream. It isn’t ment to be used several times in a row. You should serialize one thing and that’s what you will get back when you deserialize the stream. Usually you would use a data class like this one:

[System.Serializable]
public class SaveData
{
    public int highscore = 0;
    public int collectedPoints = 0;
    public int lifetimeScore = 0;
}

You can either create a temporary instance of that class, assign your values to the fields and then serialize it, or directly replace your static variables with a single variables to an instance of that SaveData class.

public static SaveData data = new SaveData();

That way you always store the data directly into the instance. To access a value you would need to use

MyScript.data.highscore = 42;
// instead of
MyScript.highscore = 42;

Now you can simply serialize and deserialize your SaveData class. When you deserialize it you will simple replace the current instance with the deserialized version:

data = (SaveData)bf.Deserialize(file);