Unity 2D:Highscore 的 PlayerPrefs 实现

Unity 2D: PlayerPrefs Implementation for Highscore

我需要一些帮助来实现可保存的 HighScore。目前,我有一个分数,从 500,000 开始,每秒下降 150 分。这行得通,尽管我死后它仍在继续,我需要修复它。我有第二个 kmHighscore 文本,我希望它显示高分。现在它显示了我死亡的确切分数(例如 450,875),但是当我重新启动游戏时我似乎无法保存它。我尝试使用 PlayerPrefs,但不确定如何在我的代码中应用它。我希望它代表最低的分数,在这种情况下,它从 500,000 开始,达到有史以来的分数。请注意:kmScore 和 kmHighscore 都只是数字,我在 Unity window 中的分数或高分之前没有文本。任何帮助将不胜感激!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class GameOver : MonoBehaviour {

    public GameObject gameOverScreen;
    public Text kmScore;
    public Text kmHighscore;
    float savedScore;
    bool gameOver;
    private float score = 500000;

    void Start () {
        FindObjectOfType<PlayerController>().OnPlayerDeath += OnGameOver;          
    }

    public void Update () {

        kmScore.text = GetScore().ToString("F0");

        if (gameOver)
        {
            if (Input.GetKeyDown (KeyCode.Space))
            {
                SceneManager.LoadScene(1);
            }
        }
    }


    float GetScore()
    {
        return score - (float)Time.timeSinceLevelLoad * 150;
    }


    void OnGameOver()
    {

        gameOverScreen.SetActive (true);
        kmHighscore.text = GetScore().ToString("F0");

    }
}

您应该将脚本更改为:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class GameOver : MonoBehaviour {
    const string PLAYERPREFS_HIGHSCORE = "High Score";
    const int STARTING_SCORE = 500000, POINTS_PER_SECOND = 150;
    public GameObject gameOverScreen;
    public Text kmScore, kmHighscore;
    private int allTimeHighScore, actualScore;
    private bool gameOver;

    private void Start() {
        allTimeHighScore = PlayerPrefs.GetInt(PLAYERPREFS_HIGHSCORE, STARTING_SCORE);
        gameOver = false;
        FindObjectOfType<PlayerController>().OnPlayerDeath += OnGameOver;
        kmHighscore.text = allTimeHighScore.ToString("F0");
    }

    private void Update() {
        if (gameOver) {
            if (Input.GetKeyDown(KeyCode.Space)) {
                SceneManager.LoadScene(1);
            }
        }
        else {
            kmScore.text = GetScore().ToString("F0");
        }
    }

    private int GetScore() {
        return actualScore = STARTING_SCORE - (int)Time.timeSinceLevelLoad * POINTS_PER_SECOND;
    }

    private void OnGameOver() {
        gameOverScreen.SetActive(true);
        if (allTimeHighScore > GetScore()) {
            kmHighscore.text = (allTimeHighScore = actualScore).ToString("F0");
            PlayerPrefs.SetInt(PLAYERPREFS_HIGHSCORE, allTimeHighScore);
        }
        gameOver = true;
    }
}

关于代码的几个注释:

  • 切勿在脚本中使用所谓的 "magic numbers",如果这些变量不可变,请利用这些变量。
  • 我添加了对 gameOver 的使用,因为您将其声明为 private,并且在 class 中的任何地方都没有使用它。这将在设置为 true.
  • 时停止计分
  • 将分数类型更改为 int,这更合适。