-1
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Resolved. All i had to do was in my Save method, provide alternate value when highscore is not reached.

The file is created every time Save is called. So, previous value is overwritten only if it was less than current score. May be I could have a condition to check if file exists and update it only if the score is higher than high score.

if (score > highscore) {
            data.highScore = score;
        } 
        else
            data.highScore = highscore;
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .