- Home /
Why isn't my high score sticking?
I am new to unity and trying to add a high score to my game. I've been at this for two hours, and feel like giving up. I would love some help on this.
Right now I have a score display script, which is separate from my high score script and displays my current score + works perfectly, and transfers from scene to scene. My high score script does the exact same thing that me score display script does, even though I want it to keep and maintain a high score instead. Here is the c# script of my score display:
TextMeshProUGUI scoreText;
GameSession gameSession;
// Start is called before the first frame update
void Start()
{
scoreText = GetComponent<TextMeshProUGUI>();
gameSession = FindObjectOfType<GameSession>();
}
// Update is called once per frame
void Update()
{
scoreText.text = gameSession.GetScore().ToString();
}
And here is my high score script:
TextMeshProUGUI highScore;
TextMeshProUGUI score;
GameSession gameSession;
// Start is called before the first frame update
void Start()
{
highScore = GetComponent<TextMeshProUGUI>();
score = GetComponent<TextMeshProUGUI>();
gameSession = FindObjectOfType<GameSession>();
highScore.text = PlayerPrefs.GetInt("HighScore", 0).ToString();
}
// Update is called once per frame
void Update()
{
int number = gameSession.GetScore();
score.text = number.ToString();
if (number > PlayerPrefs.GetInt("HighScore", 0))
{
PlayerPrefs.SetInt("HighScore", number);
highScore.text = number.ToString();
}
}
both of these scripts call the number from a different script, called game session to actually get the score. Let me know if you need to see that script too, otherwise, please help me figure out how to make this work!
Hi @cvevea3 First of all, using PlayerPrefs that get checked/modified repeatedly in update is a wrong practice. Secondly, are you sure that gameSession in highScore script doesn't return a null value? $$anonymous$$aybe some null exceptions in console in run mode?
Answer by iagam · Dec 22, 2019 at 11:25 AM
remove 0 from PlayerPrefs.GetInt write PlayerPrefs.Save() when setting a new value in PlayerPrefs.
Hope this helps @cvevea3
I'm really sorry, but I'm new to unity, do you $$anonymous$$d showing me what you mean from my code? I understand removing the zeros, but where do I do PlayerPrefs.Save()?
Answer by hameed-ullah-jan · Dec 23, 2019 at 02:02 PM
Replace this Line everywhere ' PlayerPrefs.GetInt("HighScore", 0) ' , by ' PlayerPrefs.GetInt("HighScore") '