下一关
本课属于 Coddy Unity 学习旅程的“打造真正的游戏”单元。第 19 课,共 60 课。
构建中的场景列表里,每个场景都有一个编号,也就是它的构建索引:第一个是 0,下一个是 1,以此类推。LoadScene 可以接收这个编号或场景名称,SceneManager.sceneCountInBuildSettings 则表示列表中有多少个场景。如果关卡按顺序排列在列表中,下一个关卡的索引就是当前活动场景的索引加 1。这个出口会加载下一个关卡,而在最后一个关卡之后则会停止:
void OnTriggerEnter(Collider other)
{
if (!other.CompareTag("Player")) return;
int next = SceneManager.GetActiveScene().buildIndex + 1;
if (next < SceneManager.sceneCountInBuildSettings)
{
SceneManager.LoadScene(next);
}
else
{
Debug.Log("You finished the game!");
}
}如果有 4 个场景,索引就是 0 到 3,而 sceneCountInBuildSettings 的值为 4。因此,在最后一个关卡中,next 的值是 4,比列表末尾多 1。这就是为什么要用 next < sceneCountInBuildSettings 进行判断:LoadScene(4) 不会加载任何场景,还会记录 Unity 的错误 Cannot load scene: Invalid scene name (empty string) and invalid build index 4。
现在,一个出口脚本就能用于所有关卡,而且不需要在脚本中指定任何场景名称。要添加关卡,只需将对应场景添加到列表中;要更改顺序,只需在列表中拖动场景。
挑战
简单让每个目标都打开下一关。
- 在
Start()中,将"Level " + level + " of " + levels显示在levelText中:level是当前场景的buildIndex,levels是SceneManager.sceneCountInBuildSettings - 1。 - 在
OnTriggerEnter中,玩家触发时,加载buildIndex + 1;如果它不小于sceneCountInBuildSettings,则加载0(菜单)。
按“开始”,完成全部 3 关:菜单会再次出现。然后按“检查”。
亲手试试
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
public class Goal : MonoBehaviour
{
public TMP_Text levelText;
void Start()
{
// 显示 "Level 2 of 3":当前关卡的编号和关卡总数
}
void OnTriggerEnter(Collider other)
{
// 玩家到达终点:加载下一关,或者在最后一关结束后加载菜单
}
}
打造真正的游戏中的所有课
自己练习: Unity 在线编辑器