Storing high score

public class Score : MonoBehaviour {

    ArcadeScore scoreSys;

    void Start()
    {
        GameObject obj = GameObject.Find("ScoreSystem");
        scoreSys = obj.GetComponent<ArcadeScore>();
    }

    void Update() {
        if (scoreSys.score == 0) {
            PlayerPrefs.SetInt("arcadeScore", scoreSys.score);
            PlayerPrefs.Save();
        }
    }

    void OnTriggerEnter2D(Collider2D coll)
    {
        if (coll.tag == "Ball")
        {
            scoreSys.score++;
            PlayerPrefs.SetInt("arcadeScore", scoreSys.score);
            PlayerPrefs.Save();
        }
    }
}

The code above is used to detect collision and increase the score value

public class ArcadeScore : MonoBehaviour {

    public int score, cs;

    void Start()
    {
        cs = PlayerPrefs.GetInt("arcadeHighscore");
        score = 0;
    }

    void Update() {
        if (score > cs) {
            PlayerPrefs.SetInt("arcadeHighscore", score);
            PlayerPrefs.Save();
        }
    }
}

This script is supposed to increase score and in case the new score is greater than the old one, that should be the new highscore.
The problem I have is that every time when I try to set the value cs to the latest score, it always sets to 0 and my highscore doesn’t work. How can I fix that?

You set the PlayerPrefs value in two places:

if (score > cs) {
  PlayerPrefs.SetInt("arcadeHighscore", score);

Here, you check if the score is actually higher.

But you also set the value here:

scoreSys.score++;
PlayerPrefs.SetInt("arcadeScore", scoreSys.score);

without checking whether the new score is actually higher. You need to remove this bit.

While we’re at it, there is no need to have the ArcadeScore component check every frame whether or not the score is a new high score. It’s way more clean to just check when the score value has changed.

One way to do this is like this.

Change the two variables to private:

private int score, cs;

Then, add a new method like this:

public void ChangeScore(int amount)
{
  score += amount;
  if (score > cs)
  {
    PlayerPrefs.SetInt("arcadeHighscore", score);
    PlayerPrefs.Save();
   }
}

You can then remove the Update method completely.

In the Score class, do this now instead of the old code:

if (coll.CompareTag("Ball"))
{
  scoreSys.UpdateScore(1);
}

And as soon as you do that, you can actually merge the two classes.

I think in void Start(), on the second script, you did put “score = 0” so every time it will set your highscore to 0 !