Menu
CoddyTech

最佳用时

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

平台游戏的最后一步:玩家现在可以奔跑、跳跃、乘坐载具、重生、收集宝石并进入下一关,每一关都会在 PlayerPrefs 中保存最佳用时。

challenge icon

挑战

中等

每个关卡都会记住自己的最佳用时。

  1. 在 FinishLine 中添加 using TMPro;、[SerializeField] private TMP_Text bestText;,并添加一个通过 Time.deltaTime 递增的运行时间。
  2. 在 Start() 中,显示保存在 BestTime_ 加上关卡名称下的最佳成绩,格式为 Best: 12.4 s,如果没有成绩,则显示 Best: none。
  3. 到达终点时,在加载场景之前,保存首次或更快的运行时间。

按下“开始”,记录一个用时,然后打破它。接着按“检查”。

亲手试试

using UnityEngine;
using UnityEngine.SceneManagement;

public class FinishLine : MonoBehaviour
{
    void OnTriggerEnter(Collider other)
    {
        if (other.GetComponent<Player>() == null) return;

        Scene level = SceneManager.GetActiveScene();
        Debug.Log(level.name + " complete!");
        int next = level.buildIndex + 1;
        if (next >= SceneManager.sceneCountInBuildSettings)
        {
            next = 0;
        }
        SceneManager.LoadScene(next);
    }
}
quiz icon自我测试

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

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

自己练习: Unity 在线编辑器