我目前正在开发一个带有生成的 LevelController 脚本的游戏,该脚本可以在所有敌人被击败后进入下一个级别,并且应该在最后一个级别完成后返回到 Level1。
由于游戏对象和脚本的代码不断变化,我想避免在脚本中硬编码最大关卡数或在每个场景的单个游戏对象上设置变量。
我目前有三个场景(通过“文件 -> 构建设置”菜单添加),只是为了测试它们之间的转换功能。随着我提出新的想法,级别的数量可能会有所不同,并且其中的代码和对象可能会发生重大变化。
如果找不到场景,是否有一种简单的方法来捕获错误?
** 示例代码(未捕获错误)- 请参阅 LoadScene 方法 **...
public void LoadScene()
{
string nextLevelName = "Level" + _nextLevelIndex;
try
{
SceneManager.LoadScene(nextLevelName);
// Debug.Log($"Loaded {nextLevelName}.");
}
catch (Exception e)
{
Debug.Log(e);
_nextLevelIndex = 1; // reset to first Scene after final stage complete
nextLevelName = "Level" + _nextLevelIndex;
SceneManager.LoadScene(nextLevelName);
}
}```
使用 SceneManager.sceneCountInBuildSettings 它有助于获取场景的数量。我对你的代码做了一些修改,看看它是否有效。更新了 sceneCountInBuildSettings
public void LoadScene()
{
int maxBuildIndex = SceneManager.sceneCountInBuildSettings - 1;
string nextLevelName = "Level" + _nextLevelIndex;
Scene nextScene = SceneManager.GetSceneByBuildIndex(_nextLevelIndex);
if (nextScene.name == null || _nextLevelIndex > maxBuildIndex)
{
_nextLevelIndex = 1; // reset to first Scene after final stage complete
nextLevelName = "Level" + _nextLevelIndex;
}
try
{
SceneManager.LoadScene(nextLevelName);
// Debug.Log($"Loaded {nextLevelName}.");
_nextLevelIndex++; // Increment the next level index for the next scene transition
}
catch (Exception e)
{
Debug.Log(e);
}