High score value remains constant in game over scene, even if player has scored higher.

I am trying to set up a high score system for an infinite runner game, but the text always remains stuck at 21, any solution for this?

The code is given below:

For setting High Score and normal Score:

 using UnityEngine;
 using UnityEngine.UI;

 public class Score : MonoBehaviour
 {

     public Transform player;
     public Text ScoreValue; //means, input is required(the text that needs to be constantly updated i.e.           score), since a variable has been created

     // Update is called once per frame
     void Update()
     {
         int scoreValInt = Mathf.RoundToInt((player.position.z - 18) / 20);
         

         ScoreValue.text = ((player.position.z-18)/20).ToString("0"); //to string 0 to remove all decimal points
         PlayerPrefs.SetString("CurrentScore", (scoreValInt.ToString("0"))); //earlier it was .z-15/10

         PlayerPrefs.SetInt("IntHighScore", scoreValInt);
         Debug.Log(PlayerPrefs.GetInt("IntHighScore"));

         if (scoreValInt > PlayerPrefs.GetInt("IntHighScore"))
         {
             PlayerPrefs.SetString("HighScore", (scoreValInt.ToString("0")));
         }
   
     }
 }

For Displaying High Score on Game Over scene:
using UnityEngine;
using UnityEngine.UI;

 public class HighScore : MonoBehaviour
 {

     public Text ValueToUpdate;

     // Start is called before the first frame update
     void Start()
     {
         ValueToUpdate.text = PlayerPrefs.GetString("HighScore", "0").ToString();
     }

 }

I have two scenes, i) Game Scene and ii) Game Over Scene
When the game ends the scene transitions to Game Over scene using Scene Management(done in another script). The main score gets updated every time the game ends, but for the High Score, even if the score is higher than the previously set high score, the High Score in Game Over scene does not get updated and for some reason it is stuck at 21, can someone give me a solution for this? It’d be very much appreciated :slight_smile:

PlayerPrefs.SetInt(“IntHighScore”, scoreValInt);

      if (scoreValInt > PlayerPrefs.GetInt("IntHighScore"))
      {
          PlayerPrefs.SetString("HighScore", (scoreValInt.ToString("0")));
      }

The condition can’t be true since you set the value IntHighScore to scoreValue then you test if scoreValue is greater than IntHighScore.

Instead, do:

      ScoreValue.text = ((player.position.z-18)/20).ToString("0");
      PlayerPrefs.SetInt("CurrentScore", scoreValInt);
      if (scoreValInt > PlayerPrefs.GetInt("HighScore"))
      {
          PlayerPrefs.SetInt("HighScore", scoreValInt);
      }

  void Start()
  {
      ValueToUpdate.text = PlayerPrefs.GetInt("HighScore", 0).ToString("0");
  }