简体   繁体   中英

Storing Highscore in Unity C# code not working

So, I've been trying to store highscore of my player but no matter how much I try the return is 0.

Here's the score setting

  highScore = playerScoref();
           if(PlayerPrefs.GetFloat("Score") < highScore) {
                PlayerPrefs.SetFloat("Score", highScore);
            }
            PlayerPrefs.Save();
       }    

and this is where I get back the code

       Debug.Log("GAME OVER");
       highScore = PlayerPrefs.GetFloat("Score");
       Debug.Log(highScore);

I think you need to do something like this

public class Test : MonoBehaviour {

    private int ingameScore;
    private int highScore;
    private bool gameOver;
    private bool callOnce;

    void Start() {
        if (PlayerPrefs.HasKey("HighScore")) {
            highScore = PlayerPrefs.GetInt("HighScore");
        }
        else {
            //creating the key for highscore
            PlayerPrefs.SetInt("HighScore", 0);
            highScore = 0;
        }
    }

    void Update() {

        //if player lost the game set gameover boolean to true
        //and use callOnce boolean to call these block only once and only for one frame
        //to avoid extra cpu usage
        if (gameOver && !callOnce) {

            //and check if player collected higher score then highscore is and assign it 
            //to playerpref's highscore key 
            if(ingameScore > highScore) {
                PlayerPrefs.SetInt("HighScore", ingameScore);
            }

            callOnce = true;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM