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

ArgumentException:待卸载场景无效,求问题原因及解决方法

问题原因及解决方案

为什么会出现“Scene to unload is invalid”错误?

结合你的代码,主要有以下几个核心原因:

  • 单场景加载模式自动卸载了目标场景
    SceneManager.LoadScene()默认使用LoadSceneMode.Single模式,执行这行代码时,Unity会自动卸载当前所有已加载的场景。比如按D键时,先执行LoadScene("blue"),此时原来的场景(包括"red")已经被自动卸载,后续调用UnloadSceneAsync("red")时,"red"场景根本不在加载状态,自然会触发无效报错。

  • 目标场景从未被加载过
    如果程序启动时加载的场景既不是"red"也不是"blue",第一次按D键加载"blue"后,尝试卸载"red",但"red"从未被加载到内存中,卸载操作会直接判定无效。

  • 场景未配置或名称不匹配
    如果"red"或"blue"场景没添加到File -> Build Settings的Scenes In Build列表中,或者代码里的场景名称和Build Settings里的名称(含大小写)不一致,Unity会找不到对应场景,导致卸载失败。

修复方案

根据你的需求,分两种场景处理:

情况1:单场景切换(每次仅保留一个场景)

这种场景下无需手动调用卸载,LoadSceneMode.Single会自动处理旧场景的卸载,直接删除UnloadSceneAsync相关代码即可:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManager;

public class LoadScene : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKey("d"))
        {
            SceneManager.LoadScene("blue");
        }
        if (Input.GetKey("a"))
        {
            SceneManager.LoadScene("red");
        }
    }
}

情况2:多场景叠加(同时加载多个场景)

如果需要同时加载多个场景,改用LoadSceneMode.Additive模式,并且卸载前先校验场景有效性:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManager;

public class LoadScene : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKey("d"))
        {
            // 叠加加载blue场景
            SceneManager.LoadScene("blue", LoadSceneMode.Additive);
            // 检查red场景是否有效再执行卸载
            Scene redScene = SceneManager.GetSceneByName("red");
            if (redScene.IsValid())
            {
                SceneManager.UnloadSceneAsync(redScene);
            }
        }
        if (Input.GetKey("a"))
        {
            SceneManager.LoadScene("red", LoadSceneMode.Additive);
            Scene blueScene = SceneManager.GetSceneByName("blue");
            if (blueScene.IsValid())
            {
                SceneManager.UnloadSceneAsync(blueScene);
            }
        }
    }
}

额外注意事项

  • 务必把"red"和"blue"场景添加到Build Settings的Scenes In Build列表中,否则加载、卸载操作都会失败。
  • 保证代码中的场景名称和Build Settings里的完全一致(Unity场景名称区分大小写)。

内容的提问来源于stack exchange,提问作者Andy Diamond Ortiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:42:34