- Home /
[Persistence] Saved To File, Not Updating
I was able to properly save a highscore and load it up; However, when the player reaches a new highscore, it doesn't update the saved value. It ends up showing the first highscore again.
public void DiedAni()
{
if (File.Exists(Application.persistentDataPath + "/HighscoreData.HiZarrar"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/HighscoreData.HiZarrar", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
if (data.Highscore < Mathf.Floor(player.transform.position.z))
{
data.Highscore = Mathf.Floor(player.transform.position.z);
bf.Serialize(file, data);
}
file.Close();
}
else
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/HighscoreData.HiZarrar");
PlayerData data = new PlayerData
{
Highscore = Mathf.Floor(player.transform.position.z)
};
bf.Serialize(file, data);
file.Close();
}
StartCoroutine(YeahIDied());
}
If anyone could help, it'd be appreciated. I'm no longer working on this project but it would be good to know for future endeavors.
Answer by Pakillottk · Sep 28, 2018 at 02:44 AM
Looks like you're opening the file without write permissions.
Try changing this line: FileStream file = File.Open(Application.persistentDataPath + "/HighscoreData.HiZarrar", FileMode.Open);
For this: FileStream file = File.Open(Application.persistentDataPath + "/HighscoreData.HiZarrar", FileMode.Open, FileAccess.Write);
I did as you said and it gave me an error: "The stream doesn't support reading."
Ups, I told you the wrong FileAcess. Try: FileAccess.ReadWrite.
That removed the error message but it still didn't update the value.