highscore update not working in 2dunity game

Viewed 96

I'm a beginner at 2D Unity game development and this is my first game. In this game I have two scenes - one is playing scene and another is game over scene. When I try to display the high score in game over scene, it is not working for me. Here is the code I tried:

public class highscore : MonoBehaviour {
    public Text hscore;

    private void Start() {
        hscore.text = PlayerPrefs.GetInt("highscore", 0).ToString();
    }

    public void Update() {
        if (GetComponent<Score>().score > PlayerPrefs.GetInt("highscore")) { 
            PlayerPrefs.SetInt("highscore", GetComponent<Score>().score);
            hscore.text = GetComponent<Score>().score.ToString();
        }
    }
}

It freezes the game over scene and nothing else s working on that. Does anyone know what the problem is? Any help would be useful. Thanks in advance.

2 Answers

I suggest you to rework your code completely. For example why do you need additional screen just for a showing the high score. The switching between the scenes is somewhat of a costly operation. And even if you do need two screens You should put the "show high score" logic outside of your update method for sure. Now to the solution: The easiest way to handle this is by using PlayerPrefs to update the high score like so PlayerPrefs.SetInt("HighScore", yourScore); you can get the value like so: int highScore = PlayerPrefs.GetInt("HighScore", 0); The second param is optional it's return if there is no HighScore set before that. The other thing is that you could use a popup to display the high score. That way you don't have to switch between the scenes.

Check unity's PlayerPrefs class:

https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

As you can see GetInt() and SetInt() take a value from a dictionary. You have to save that values on disk to pass them between scenes(or to retrive them when you load your game again).

Are you using Save() before unloading the old scene? Also your score is comming from the previous scene? If yes are you using DontDestroyOnLoad(Object target) or its just a script in the "ShowScore" scene? If you don't pass it from the first scene it will just have default values, not your score. Hope i was clear enought.

Related