You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity场景加载错误捕获:无需硬编码关卡数的实现需求

解决方案

为什么你的try-catch没用?

Unity的SceneManager.LoadScene()同步加载场景时,就算指定的场景不存在,也不会抛出能被try-catch捕获的C#异常,只会在控制台输出错误日志,所以你的catch块根本不会执行。要实现通关最后一关返回Level1的逻辑,得先提前确认场景是否在Build Settings中存在。

具体实现步骤

1. 缓存Build Settings中的关卡场景名

在LevelController的Awake方法里,一次性把所有添加到Build Settings的关卡场景名存入HashSet(HashSet的存在性查询效率更高):

using UnityEngine.SceneManagement;
using System.Collections.Generic;
using System.Linq;

public class LevelController : MonoBehaviour
{
    private int _nextLevelIndex = 1;
    private HashSet<string> _validLevelScenes;

    private void Awake()
    {
        _validLevelScenes = new HashSet<string>();
        // 遍历Build Settings里的所有场景,只保留以Level开头的关卡场景
        foreach (var sceneSetting in SceneManager.GetSceneBuildSettings())
        {
            // 从场景路径中提取纯场景名(比如Assets/Scenes/Level3.unity → Level3)
            string sceneName = sceneSetting.path.Split('/').Last().Replace(".unity", "");
            if (sceneName.StartsWith("Level"))
            {
                _validLevelScenes.Add(sceneName);
            }
        }
    }

2. 修改场景加载逻辑

加载前先校验目标场景是否在缓存列表中,不存在则重置索引并切回Level1:

public void LoadScene()
    {
        string nextLevelName = "Level" + _nextLevelIndex;
        
        if (_validLevelScenes.Contains(nextLevelName))
        {
            SceneManager.LoadScene(nextLevelName);
            // 记得根据你的游戏逻辑更新_nextLevelIndex(比如击败所有敌人后自增)
            // _nextLevelIndex++;
        }
        else
        {
            // 找不到对应关卡,直接切回Level1并重置索引
            _nextLevelIndex = 1;
            SceneManager.LoadScene("Level1");
        }
    }
}

方案优势

  • 完全无需硬编码最大关卡数,后续新增关卡只需添加到Build Settings,代码自动识别
  • 不用在每个场景的游戏对象上设置变量,全程依赖Build场景列表驱动,维护成本低
  • 只要保持关卡命名为LevelX的格式,后续扩展关卡数量时无需修改逻辑

内容的提问来源于stack exchange,提问作者Rebel_47

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 22:12:32