Unity多场景运行时,如何让Update()对应GameObject所在场景为激活场景
Unity多场景下Update时激活场景自动匹配GameObject所在场景的解决方案
问题背景
同时运行SceneA和SceneB两个场景,SceneB作为SceneA的代理,需将SceneA中的完整GameObject复制到SceneB。但复制后的GameObject执行Update()时,SceneManager.GetActiveScene()返回的仍是SceneA,而非其实际所在的SceneB。
示例代码
SceneA中挂载以下脚本的GameObject:
private void Update() { Scene activeScene = SceneManager.GetActiveScene(); Scene myScene = this.gameObject.scene; Debug.Log("Active Scene is '" + activeScene.name + "'; This scene is " + myScene.name); }
- 在SceneA中运行输出:
Active Scene is SceneA; This scene is SceneA - 复制到SceneB后输出:
Active Scene is SceneA; This scene is SceneB
目标:让SceneB中的GameObject执行Update()时,激活场景自动切换为SceneB,输出Active Scene is SceneB; This scene is SceneB,且无需逐个修改原有脚本。
已尝试的方法及局限
尝试修改PlayerLoop添加自定义事件,但发现PlayerLoop的事件是跨场景交错执行的,GameObject的Update顺序甚至不按场景分组,而是按运行时创建顺序排列,无法通过场景分组来提前切换激活场景。
可行解决方案
方案1:IL注入拦截所有MonoBehaviour的Update调用(推荐)
通过IL注入,在所有MonoBehaviour.Update()方法的执行前自动插入场景切换逻辑,确保当前激活场景是GameObject所在的场景。无需修改原有脚本,全局生效。
实现步骤(使用Harmony库)
- 安装Harmony库:可通过Unity Package Manager导入
com.bepinex.harmony,或通过NuGet安装。 - 创建以下脚本:
using UnityEngine.SceneManagement; using HarmonyLib; using UnityEngine; public class SceneActiveAutoSwitcher { [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] private static void Initialize() { var harmonyInstance = new Harmony("com.yourdomain.sceneautoswitch"); harmonyInstance.PatchAll(); } [HarmonyPrefix] [HarmonyPatch(typeof(MonoBehaviour), nameof(MonoBehaviour.Update))] private static void BeforeUpdateExecution(MonoBehaviour __instance) { if (__instance == null || !__instance.gameObject.scene.isLoaded) return; Scene targetScene = __instance.gameObject.scene; if (SceneManager.GetActiveScene() != targetScene) { SceneManager.SetActiveScene(targetScene); } } }
该代码会在每一个MonoBehaviour.Update()执行前,检查并切换激活场景到当前脚本所在GameObject的场景,完美适配交错执行的情况。
方案2:自定义PlayerLoop阶段(仅适用于可按场景分组执行的场景)
若能将场景的Update逻辑调整为按场景分组执行,可通过修改PlayerLoop实现:
- 复制默认的PlayerLoop结构,拆分出每个场景的Update阶段。
- 在每个场景的Update阶段前插入切换激活场景的逻辑。
但由于用户场景中Update是交错执行的,此方案适用性有限,仅作参考。
内容的提问来源于stack exchange,提问作者ugggghhhhh
相关产品推荐
相关产品推荐

