I wanted to avoid using playerprefs because they are easy to edit. So, I went with Serialization. Here is my main class that does all the scorekeeping:
public class scoreKeeper : MonoBehaviour {
public static scoreKeeper sk;
public int score=0,highscore=0;
public bool increase=false;
void Awake(){
if (sk == null) {
DontDestroyOnLoad(gameObject);
sk=this;
}
if (sk != this)
Destroy (gameObject);
highscore=load ();
Debug.Log (highscore);
}
void Update () {
if (increase) {
score++;
increase = false;
}
}
public void save()
{
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Create (Application.persistentDataPath + "/playerInfo.dat");
PlayerData data = new PlayerData ();
if (score >data.highScore)
data.highScore = score;
bf.Serialize (file, data);
file.Close ();
highscore = load ();
}
int load()
{
if (File.Exists (Application.persistentDataPath + "/playerInfo.dat")) {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat",FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize (file);
file.Close ();
return data.highScore;
} else
return 0;
}
}
[Serializable]
class PlayerData
{
public int highScore;
}
The Save function is called at a game over condition like this: scoreKeeper.sk.save();
The problem i'm facing is, highscore keeps getting updated even when score is lower than highscore. In my Save method, I have the line if(score>data.highScore) data.highScore=score;
When I repeatedly run the game, thr high scores are 11, 2, 5, 3, etc. What is the error in my code?