最佳用时
本课属于 Coddy Unity 学习旅程的“打造真正的游戏”单元。第 56 课,共 60 课。
平台游戏的最后一步:玩家现在可以奔跑、跳跃、乘坐载具、重生、收集宝石并进入下一关,每一关都会在 PlayerPrefs 中保存最佳用时。
挑战
中等每个关卡都会记住自己的最佳用时。
- 在
FinishLine中添加using TMPro;、[SerializeField] private TMP_Text bestText;,并添加一个通过Time.deltaTime递增的运行时间。 - 在
Start()中,显示保存在BestTime_加上关卡名称下的最佳成绩,格式为Best: 12.4 s,如果没有成绩,则显示Best: none。 - 到达终点时,在加载场景之前,保存首次或更快的运行时间。
按下“开始”,记录一个用时,然后打破它。接着按“检查”。
亲手试试
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);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
打造真正的游戏中的所有课
自己练习: Unity 在线编辑器