简体   繁体   English

在 Unity C# 代码中存储高分不起作用

[英]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.所以,我一直在尝试存储我的球员的高分,但无论我尝试多少,回报都是 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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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