LaunchSceneInput.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Linq;
  3. using HotPatch;
  4. using UnityEngine;
  5. using UnityEngine.EventSystems;
  6. using UnityEngine.SceneManagement;
  7. public static class LaunchSceneInput
  8. {
  9. public static EventSystem Transfer(Scene launchScene, Scene gameScene)
  10. {
  11. if (!launchScene.IsValid() || !launchScene.isLoaded || !gameScene.IsValid() || !gameScene.isLoaded || launchScene == gameScene)
  12. throw new ArgumentException("Input transfer requires two different loaded scenes.");
  13. var gameSystems = SystemsIn(gameScene);
  14. var launchSystems = SystemsIn(launchScene);
  15. var selected = gameSystems.FirstOrDefault(IsUsable);
  16. var source = "game";
  17. if (selected == null && IsUsable(EventSystem.current) && EventSystem.current.gameObject.scene != launchScene)
  18. {
  19. selected = EventSystem.current;
  20. source = "shared";
  21. }
  22. if (selected == null)
  23. {
  24. selected = launchSystems.FirstOrDefault(IsUsable);
  25. source = "launch";
  26. }
  27. if (selected == null)
  28. {
  29. selected = new GameObject("EventSystem", typeof(EventSystem), typeof(StandaloneInputModule)).GetComponent<EventSystem>();
  30. SceneManager.MoveGameObjectToScene(selected.gameObject, gameScene);
  31. source = "created";
  32. }
  33. else if (selected.gameObject.scene == launchScene)
  34. {
  35. selected.transform.SetParent(null, true);
  36. SceneManager.MoveGameObjectToScene(selected.gameObject, gameScene);
  37. }
  38. foreach (var duplicate in launchSystems.Concat(gameSystems).Where(system => system != selected))
  39. {
  40. foreach (var module in duplicate.GetComponents<BaseInputModule>()) module.enabled = false;
  41. duplicate.enabled = false;
  42. }
  43. EventSystem.current = selected;
  44. if (selected.currentSelectedGameObject != null && selected.currentSelectedGameObject.scene == launchScene)
  45. selected.SetSelectedGameObject(null);
  46. if (selected.firstSelectedGameObject != null && selected.firstSelectedGameObject.scene == launchScene)
  47. selected.firstSelectedGameObject = null;
  48. HotPatchLog.Info("scene_input_ready source=" + source + " scene=" + selected.gameObject.scene.name +
  49. " modules=" + string.Join(",", selected.GetComponents<BaseInputModule>().Where(module => module.isActiveAndEnabled).Select(module => module.GetType().Name)));
  50. return selected;
  51. }
  52. static EventSystem[] SystemsIn(Scene scene) => scene.GetRootGameObjects()
  53. .SelectMany(root => root.GetComponentsInChildren<EventSystem>(true)).ToArray();
  54. static bool IsUsable(EventSystem system) => system != null && system.isActiveAndEnabled &&
  55. system.GetComponents<BaseInputModule>().Any(module => module.isActiveAndEnabled);
  56. }