using System; using System.Linq; using HotPatch; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.SceneManagement; public static class LaunchSceneInput { public static EventSystem Transfer(Scene launchScene, Scene gameScene) { if (!launchScene.IsValid() || !launchScene.isLoaded || !gameScene.IsValid() || !gameScene.isLoaded || launchScene == gameScene) throw new ArgumentException("Input transfer requires two different loaded scenes."); var gameSystems = SystemsIn(gameScene); var launchSystems = SystemsIn(launchScene); var selected = gameSystems.FirstOrDefault(IsUsable); var source = "game"; if (selected == null && IsUsable(EventSystem.current) && EventSystem.current.gameObject.scene != launchScene) { selected = EventSystem.current; source = "shared"; } if (selected == null) { selected = launchSystems.FirstOrDefault(IsUsable); source = "launch"; } if (selected == null) { selected = new GameObject("EventSystem", typeof(EventSystem), typeof(StandaloneInputModule)).GetComponent(); SceneManager.MoveGameObjectToScene(selected.gameObject, gameScene); source = "created"; } else if (selected.gameObject.scene == launchScene) { selected.transform.SetParent(null, true); SceneManager.MoveGameObjectToScene(selected.gameObject, gameScene); } foreach (var duplicate in launchSystems.Concat(gameSystems).Where(system => system != selected)) { foreach (var module in duplicate.GetComponents()) module.enabled = false; duplicate.enabled = false; } EventSystem.current = selected; if (selected.currentSelectedGameObject != null && selected.currentSelectedGameObject.scene == launchScene) selected.SetSelectedGameObject(null); if (selected.firstSelectedGameObject != null && selected.firstSelectedGameObject.scene == launchScene) selected.firstSelectedGameObject = null; HotPatchLog.Info("scene_input_ready source=" + source + " scene=" + selected.gameObject.scene.name + " modules=" + string.Join(",", selected.GetComponents().Where(module => module.isActiveAndEnabled).Select(module => module.GetType().Name))); return selected; } static EventSystem[] SystemsIn(Scene scene) => scene.GetRootGameObjects() .SelectMany(root => root.GetComponentsInChildren(true)).ToArray(); static bool IsUsable(EventSystem system) => system != null && system.isActiveAndEnabled && system.GetComponents().Any(module => module.isActiveAndEnabled); }