Menu
CoddyTech

最佳成绩

本课属于 Coddy Unity 学习旅程的“打造真正的游戏”单元。第 33 课,共 60 课。

无尽跑酷的最后一步:最佳成绩会像最高分一样保存在 PlayerPrefs 中,因此再次运行和退出游戏后,记录仍会保留。

challenge icon

挑战

中等

使用键 BestRun 保存最佳成绩。

  1. 添加 private int best;。在 Start() 中,使用 PlayerPrefs.GetInt("BestRun", 0) 加载它,并在 bestText 中显示 "Best: " + best + " m"。
  2. 在 GameOver() 的末尾,当 Mathf.FloorToInt(distance) 的结果超过 best 时,保存并显示该结果,然后调用 newBestText.SetActive(true);。

按“开始”,设置一个最佳成绩,然后超过它:此时会显示 New best!。然后点击“检查”。

亲手试试

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

public enum GameState { Playing, GameOver }

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public float speed = 10f;
    public float speedUp = 0.5f;
    public float maxSpeed = 20f;
    public TMP_Text distanceText;
    public GameObject gameOverPanel;
    public Button restartButton;
    public GameState state = GameState.Playing;
    public TMP_Text bestText;
    public GameObject newBestText;
    private float distance;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        restartButton.onClick.AddListener(Restart);
    }

    void Update()
    {
        if (state != GameState.Playing) return;

        speed = Mathf.Min(speed + speedUp * Time.deltaTime, maxSpeed);
        distance += speed * Time.deltaTime;
        distanceText.text = "Distance: " + Mathf.FloorToInt(distance) + " m";
    }

    public void GameOver()
    {
        state = GameState.GameOver;
        speed = 0f;
        gameOverPanel.SetActive(true);
    }

    void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

打造真正的游戏中的所有课

自己练习: Unity 在线编辑器