Sin descripción
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EventSystem.cs 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using UnityEngine;
  5. using UnityEngine.Serialization;
  6. using UnityEngine.UIElements;
  7. namespace UnityEngine.EventSystems
  8. {
  9. [AddComponentMenu("Event/Event System")]
  10. [DisallowMultipleComponent]
  11. /// <summary>
  12. /// Handles input, raycasting, and sending events.
  13. /// </summary>
  14. /// <remarks>
  15. /// The EventSystem is responsible for processing and handling events in a Unity scene. A scene should only contain one EventSystem. The EventSystem works in conjunction with a number of modules and mostly just holds state and delegates functionality to specific, overrideable components.
  16. /// When the EventSystem is started it searches for any BaseInputModules attached to the same GameObject and adds them to an internal list. On update each attached module receives an UpdateModules call, where the module can modify internal state. After each module has been Updated the active module has the Process call executed.This is where custom module processing can take place.
  17. /// </remarks>
  18. public class EventSystem : UIBehaviour
  19. {
  20. private List<BaseInputModule> m_SystemInputModules = new List<BaseInputModule>();
  21. private BaseInputModule m_CurrentInputModule;
  22. private static List<EventSystem> m_EventSystems = new List<EventSystem>();
  23. /// <summary>
  24. /// Return the current EventSystem.
  25. /// </summary>
  26. public static EventSystem current
  27. {
  28. get { return m_EventSystems.Count > 0 ? m_EventSystems[0] : null; }
  29. set
  30. {
  31. int index = m_EventSystems.IndexOf(value);
  32. if (index > 0)
  33. {
  34. m_EventSystems.RemoveAt(index);
  35. m_EventSystems.Insert(0, value);
  36. }
  37. else if (index < 0)
  38. {
  39. Debug.LogError("Failed setting EventSystem.current to unknown EventSystem " + value);
  40. }
  41. }
  42. }
  43. [SerializeField]
  44. [FormerlySerializedAs("m_Selected")]
  45. private GameObject m_FirstSelected;
  46. [SerializeField]
  47. private bool m_sendNavigationEvents = true;
  48. /// <summary>
  49. /// Should the EventSystem allow navigation events (move / submit / cancel).
  50. /// </summary>
  51. public bool sendNavigationEvents
  52. {
  53. get { return m_sendNavigationEvents; }
  54. set { m_sendNavigationEvents = value; }
  55. }
  56. [SerializeField]
  57. private int m_DragThreshold = 10;
  58. /// <summary>
  59. /// The soft area for dragging in pixels.
  60. /// </summary>
  61. public int pixelDragThreshold
  62. {
  63. get { return m_DragThreshold; }
  64. set { m_DragThreshold = value; }
  65. }
  66. private GameObject m_CurrentSelected;
  67. /// <summary>
  68. /// The currently active EventSystems.BaseInputModule.
  69. /// </summary>
  70. public BaseInputModule currentInputModule
  71. {
  72. get { return m_CurrentInputModule; }
  73. }
  74. /// <summary>
  75. /// Only one object can be selected at a time. Think: controller-selected button.
  76. /// </summary>
  77. public GameObject firstSelectedGameObject
  78. {
  79. get { return m_FirstSelected; }
  80. set { m_FirstSelected = value; }
  81. }
  82. /// <summary>
  83. /// The GameObject currently considered active by the EventSystem.
  84. /// </summary>
  85. public GameObject currentSelectedGameObject
  86. {
  87. get { return m_CurrentSelected; }
  88. }
  89. [Obsolete("lastSelectedGameObject is no longer supported")]
  90. public GameObject lastSelectedGameObject
  91. {
  92. get { return null; }
  93. }
  94. private bool m_HasFocus = true;
  95. /// <summary>
  96. /// Flag to say whether the EventSystem thinks it should be paused or not based upon focused state.
  97. /// </summary>
  98. /// <remarks>
  99. /// Used to determine inside the individual InputModules if the module should be ticked while the application doesnt have focus.
  100. /// </remarks>
  101. public bool isFocused
  102. {
  103. get { return m_HasFocus; }
  104. }
  105. protected EventSystem()
  106. {}
  107. /// <summary>
  108. /// Recalculate the internal list of BaseInputModules.
  109. /// </summary>
  110. public void UpdateModules()
  111. {
  112. GetComponents(m_SystemInputModules);
  113. var systemInputModulesCount = m_SystemInputModules.Count;
  114. for (int i = systemInputModulesCount - 1; i >= 0; i--)
  115. {
  116. if (m_SystemInputModules[i] && m_SystemInputModules[i].IsActive())
  117. continue;
  118. m_SystemInputModules.RemoveAt(i);
  119. }
  120. }
  121. private bool m_SelectionGuard;
  122. /// <summary>
  123. /// Returns true if the EventSystem is already in a SetSelectedGameObject.
  124. /// </summary>
  125. public bool alreadySelecting
  126. {
  127. get { return m_SelectionGuard; }
  128. }
  129. /// <summary>
  130. /// Set the object as selected. Will send an OnDeselect the the old selected object and OnSelect to the new selected object.
  131. /// </summary>
  132. /// <param name="selected">GameObject to select.</param>
  133. /// <param name="pointer">Associated EventData.</param>
  134. public void SetSelectedGameObject(GameObject selected, BaseEventData pointer)
  135. {
  136. if (m_SelectionGuard)
  137. {
  138. Debug.LogError("Attempting to select " + selected + "while already selecting an object.");
  139. return;
  140. }
  141. m_SelectionGuard = true;
  142. if (selected == m_CurrentSelected)
  143. {
  144. m_SelectionGuard = false;
  145. return;
  146. }
  147. // Debug.Log("Selection: new (" + selected + ") old (" + m_CurrentSelected + ")");
  148. ExecuteEvents.Execute(m_CurrentSelected, pointer, ExecuteEvents.deselectHandler);
  149. m_CurrentSelected = selected;
  150. ExecuteEvents.Execute(m_CurrentSelected, pointer, ExecuteEvents.selectHandler);
  151. m_SelectionGuard = false;
  152. }
  153. private BaseEventData m_DummyData;
  154. private BaseEventData baseEventDataCache
  155. {
  156. get
  157. {
  158. if (m_DummyData == null)
  159. m_DummyData = new BaseEventData(this);
  160. return m_DummyData;
  161. }
  162. }
  163. /// <summary>
  164. /// Set the object as selected. Will send an OnDeselect the the old selected object and OnSelect to the new selected object.
  165. /// </summary>
  166. /// <param name="selected">GameObject to select.</param>
  167. public void SetSelectedGameObject(GameObject selected)
  168. {
  169. SetSelectedGameObject(selected, baseEventDataCache);
  170. }
  171. private static int RaycastComparer(RaycastResult lhs, RaycastResult rhs)
  172. {
  173. if (lhs.module != rhs.module)
  174. {
  175. var lhsEventCamera = lhs.module.eventCamera;
  176. var rhsEventCamera = rhs.module.eventCamera;
  177. if (lhsEventCamera != null && rhsEventCamera != null && lhsEventCamera.depth != rhsEventCamera.depth)
  178. {
  179. // need to reverse the standard compareTo
  180. if (lhsEventCamera.depth < rhsEventCamera.depth)
  181. return 1;
  182. if (lhsEventCamera.depth == rhsEventCamera.depth)
  183. return 0;
  184. return -1;
  185. }
  186. if (lhs.module.sortOrderPriority != rhs.module.sortOrderPriority)
  187. return rhs.module.sortOrderPriority.CompareTo(lhs.module.sortOrderPriority);
  188. if (lhs.module.renderOrderPriority != rhs.module.renderOrderPriority)
  189. return rhs.module.renderOrderPriority.CompareTo(lhs.module.renderOrderPriority);
  190. }
  191. if (lhs.sortingLayer != rhs.sortingLayer)
  192. {
  193. // Uses the layer value to properly compare the relative order of the layers.
  194. var rid = SortingLayer.GetLayerValueFromID(rhs.sortingLayer);
  195. var lid = SortingLayer.GetLayerValueFromID(lhs.sortingLayer);
  196. return rid.CompareTo(lid);
  197. }
  198. if (lhs.sortingOrder != rhs.sortingOrder)
  199. return rhs.sortingOrder.CompareTo(lhs.sortingOrder);
  200. // comparing depth only makes sense if the two raycast results have the same root canvas (case 912396)
  201. if (lhs.depth != rhs.depth && lhs.module.rootRaycaster == rhs.module.rootRaycaster)
  202. return rhs.depth.CompareTo(lhs.depth);
  203. if (lhs.distance != rhs.distance)
  204. return lhs.distance.CompareTo(rhs.distance);
  205. return lhs.index.CompareTo(rhs.index);
  206. }
  207. private static readonly Comparison<RaycastResult> s_RaycastComparer = RaycastComparer;
  208. /// <summary>
  209. /// Raycast into the scene using all configured BaseRaycasters.
  210. /// </summary>
  211. /// <param name="eventData">Current pointer data.</param>
  212. /// <param name="raycastResults">List of 'hits' to populate.</param>
  213. public void RaycastAll(PointerEventData eventData, List<RaycastResult> raycastResults)
  214. {
  215. raycastResults.Clear();
  216. var modules = RaycasterManager.GetRaycasters();
  217. var modulesCount = modules.Count;
  218. for (int i = 0; i < modulesCount; ++i)
  219. {
  220. var module = modules[i];
  221. if (module == null || !module.IsActive())
  222. continue;
  223. module.Raycast(eventData, raycastResults);
  224. }
  225. raycastResults.Sort(s_RaycastComparer);
  226. }
  227. /// <summary>
  228. /// Is the pointer with the given ID over an EventSystem object?
  229. /// </summary>
  230. public bool IsPointerOverGameObject()
  231. {
  232. return IsPointerOverGameObject(PointerInputModule.kMouseLeftId);
  233. }
  234. /// <summary>
  235. /// Is the pointer with the given ID over an EventSystem object?
  236. /// </summary>
  237. /// <remarks>
  238. /// If you use IsPointerOverGameObject() without a parameter, it points to the "left mouse button" (pointerId = -1); therefore when you use IsPointerOverGameObject for touch, you should consider passing a pointerId to it
  239. /// Note that for touch, IsPointerOverGameObject should be used with ''OnMouseDown()'' or ''Input.GetMouseButtonDown(0)'' or ''Input.GetTouch(0).phase == TouchPhase.Began''.
  240. /// </remarks>
  241. /// <example>
  242. /// <code>
  243. /// <![CDATA[
  244. /// using UnityEngine;
  245. /// using System.Collections;
  246. /// using UnityEngine.EventSystems;
  247. ///
  248. /// public class MouseExample : MonoBehaviour
  249. /// {
  250. /// void Update()
  251. /// {
  252. /// // Check if the left mouse button was clicked
  253. /// if (Input.GetMouseButtonDown(0))
  254. /// {
  255. /// // Check if the mouse was clicked over a UI element
  256. /// if (EventSystem.current.IsPointerOverGameObject())
  257. /// {
  258. /// Debug.Log("Clicked on the UI");
  259. /// }
  260. /// }
  261. /// }
  262. /// }
  263. /// ]]>
  264. ///</code>
  265. /// </example>
  266. public bool IsPointerOverGameObject(int pointerId)
  267. {
  268. return m_CurrentInputModule != null && m_CurrentInputModule.IsPointerOverGameObject(pointerId);
  269. }
  270. #if PACKAGE_UITOOLKIT
  271. private struct UIToolkitOverrideConfig
  272. {
  273. public EventSystem activeEventSystem;
  274. public bool sendEvents;
  275. public bool createPanelGameObjectsOnStart;
  276. }
  277. private static UIToolkitOverrideConfig s_UIToolkitOverride = new UIToolkitOverrideConfig
  278. {
  279. activeEventSystem = null,
  280. sendEvents = true,
  281. createPanelGameObjectsOnStart = true
  282. };
  283. private bool isUIToolkitActiveEventSystem =>
  284. s_UIToolkitOverride.activeEventSystem == this || s_UIToolkitOverride.activeEventSystem == null;
  285. private bool sendUIToolkitEvents =>
  286. s_UIToolkitOverride.sendEvents && isUIToolkitActiveEventSystem;
  287. private bool createUIToolkitPanelGameObjectsOnStart =>
  288. s_UIToolkitOverride.createPanelGameObjectsOnStart && isUIToolkitActiveEventSystem;
  289. #endif
  290. /// <summary>
  291. /// Sets how UI Toolkit runtime panels receive events and handle selection
  292. /// when interacting with other objects that use the EventSystem, such as components from the Unity UI package.
  293. /// </summary>
  294. /// <param name="activeEventSystem">
  295. /// The EventSystem used to override UI Toolkit panel events and selection.
  296. /// If activeEventSystem is null, UI Toolkit panels will use current enabled EventSystem
  297. /// or, if there is none, the default InputManager-based event system will be used.
  298. /// </param>
  299. /// <param name="sendEvents">
  300. /// If true, UI Toolkit events will come from this EventSystem
  301. /// instead of the default InputManager-based event system.
  302. /// </param>
  303. /// <param name="createPanelGameObjectsOnStart">
  304. /// If true, UI Toolkit panels' unassigned selectableGameObject will be automatically initialized
  305. /// with children GameObjects of this EventSystem on Start.
  306. /// </param>
  307. public static void SetUITookitEventSystemOverride(EventSystem activeEventSystem, bool sendEvents = true, bool createPanelGameObjectsOnStart = true)
  308. {
  309. #if PACKAGE_UITOOLKIT
  310. UIElementsRuntimeUtility.UnregisterEventSystem(UIElementsRuntimeUtility.activeEventSystem);
  311. s_UIToolkitOverride = new UIToolkitOverrideConfig
  312. {
  313. activeEventSystem = activeEventSystem,
  314. sendEvents = sendEvents,
  315. createPanelGameObjectsOnStart = createPanelGameObjectsOnStart,
  316. };
  317. if (sendEvents)
  318. {
  319. var eventSystem = activeEventSystem != null ? activeEventSystem : EventSystem.current;
  320. if (eventSystem.isActiveAndEnabled)
  321. UIElementsRuntimeUtility.RegisterEventSystem(activeEventSystem);
  322. }
  323. #endif
  324. }
  325. #if PACKAGE_UITOOLKIT
  326. private void CreateUIToolkitPanelGameObject(BaseRuntimePanel panel)
  327. {
  328. if (panel.selectableGameObject == null)
  329. {
  330. var go = new GameObject(panel.name, typeof(PanelEventHandler), typeof(PanelRaycaster));
  331. go.transform.SetParent(transform);
  332. panel.selectableGameObject = go;
  333. panel.destroyed += () => DestroyImmediate(go);
  334. }
  335. }
  336. #endif
  337. protected override void Start()
  338. {
  339. base.Start();
  340. #if PACKAGE_UITOOLKIT
  341. if (createUIToolkitPanelGameObjectsOnStart)
  342. {
  343. foreach (BaseRuntimePanel panel in UIElementsRuntimeUtility.GetSortedPlayerPanels())
  344. {
  345. CreateUIToolkitPanelGameObject(panel);
  346. }
  347. UIElementsRuntimeUtility.onCreatePanel += CreateUIToolkitPanelGameObject;
  348. }
  349. #endif
  350. }
  351. protected override void OnDestroy()
  352. {
  353. #if PACKAGE_UITOOLKIT
  354. UIElementsRuntimeUtility.onCreatePanel -= CreateUIToolkitPanelGameObject;
  355. #endif
  356. base.OnDestroy();
  357. }
  358. protected override void OnEnable()
  359. {
  360. base.OnEnable();
  361. m_EventSystems.Add(this);
  362. #if PACKAGE_UITOOLKIT
  363. if (sendUIToolkitEvents)
  364. {
  365. UIElementsRuntimeUtility.RegisterEventSystem(this);
  366. }
  367. #endif
  368. }
  369. protected override void OnDisable()
  370. {
  371. #if PACKAGE_UITOOLKIT
  372. UIElementsRuntimeUtility.UnregisterEventSystem(this);
  373. #endif
  374. if (m_CurrentInputModule != null)
  375. {
  376. m_CurrentInputModule.DeactivateModule();
  377. m_CurrentInputModule = null;
  378. }
  379. m_EventSystems.Remove(this);
  380. base.OnDisable();
  381. }
  382. private void TickModules()
  383. {
  384. var systemInputModulesCount = m_SystemInputModules.Count;
  385. for (var i = 0; i < systemInputModulesCount; i++)
  386. {
  387. if (m_SystemInputModules[i] != null)
  388. m_SystemInputModules[i].UpdateModule();
  389. }
  390. }
  391. protected virtual void OnApplicationFocus(bool hasFocus)
  392. {
  393. m_HasFocus = hasFocus;
  394. if (!m_HasFocus)
  395. TickModules();
  396. }
  397. protected virtual void Update()
  398. {
  399. if (current != this)
  400. return;
  401. TickModules();
  402. bool changedModule = false;
  403. var systemInputModulesCount = m_SystemInputModules.Count;
  404. for (var i = 0; i < systemInputModulesCount; i++)
  405. {
  406. var module = m_SystemInputModules[i];
  407. if (module.IsModuleSupported() && module.ShouldActivateModule())
  408. {
  409. if (m_CurrentInputModule != module)
  410. {
  411. ChangeEventModule(module);
  412. changedModule = true;
  413. }
  414. break;
  415. }
  416. }
  417. // no event module set... set the first valid one...
  418. if (m_CurrentInputModule == null)
  419. {
  420. for (var i = 0; i < systemInputModulesCount; i++)
  421. {
  422. var module = m_SystemInputModules[i];
  423. if (module.IsModuleSupported())
  424. {
  425. ChangeEventModule(module);
  426. changedModule = true;
  427. break;
  428. }
  429. }
  430. }
  431. if (!changedModule && m_CurrentInputModule != null)
  432. m_CurrentInputModule.Process();
  433. #if UNITY_EDITOR
  434. if (Application.isPlaying)
  435. {
  436. int eventSystemCount = 0;
  437. for (int i = 0; i < m_EventSystems.Count; i++)
  438. {
  439. if (m_EventSystems[i].GetType() == typeof(EventSystem))
  440. eventSystemCount++;
  441. }
  442. if (eventSystemCount > 1)
  443. Debug.LogWarning("There are " + eventSystemCount + " event systems in the scene. Please ensure there is always exactly one event system in the scene");
  444. }
  445. #endif
  446. }
  447. private void ChangeEventModule(BaseInputModule module)
  448. {
  449. if (m_CurrentInputModule == module)
  450. return;
  451. if (m_CurrentInputModule != null)
  452. m_CurrentInputModule.DeactivateModule();
  453. if (module != null)
  454. module.ActivateModule();
  455. m_CurrentInputModule = module;
  456. }
  457. public override string ToString()
  458. {
  459. var sb = new StringBuilder();
  460. sb.AppendLine("<b>Selected:</b>" + currentSelectedGameObject);
  461. sb.AppendLine();
  462. sb.AppendLine();
  463. sb.AppendLine(m_CurrentInputModule != null ? m_CurrentInputModule.ToString() : "No module");
  464. return sb.ToString();
  465. }
  466. }
  467. }