在Unity C#代码中存储Highscore无效

时间:2019-10-28 08:21:19

标签: c# unity3d mobile game-engine

因此,我一直在尝试存储播放器的高分,但无论我尝试多少,返回值为0。

这是分数设置

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

这是我取回代码的地方

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

1 个答案:

答案 0 :(得分:0)

我认为您需要做类似的事情

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;
        }
    }
}