EventSystem.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using UnityEngine;
  5. using UnityEngine.Serialization;
  6. namespace UnityEngine.EventSystems
  7. {
  8. [AddComponentMenu("Event/Event System")]
  9. [DisallowMultipleComponent]
  10. /// <summary>
  11. /// Handles input, raycasting, and sending events.
  12. /// </summary>
  13. /// <remarks>
  14. /// 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.
  15. /// 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.
  16. /// </remarks>
  17. public class EventSystem : UIBehaviour
  18. {
  19. private List<BaseInputModule> m_SystemInputModules = new List<BaseInputModule>();
  20. private BaseInputModule m_CurrentInputModule;
  21. private static List<EventSystem> m_EventSystems = new List<EventSystem>();
  22. /// <summary>
  23. /// Return the current EventSystem.
  24. /// </summary>
  25. public static EventSystem current
  26. {
  27. get { return m_EventSystems.Count > 0 ? m_EventSystems[0] : null; }
  28. set
  29. {
  30. int index = m_EventSystems.IndexOf(value);
  31. if (index > 0)
  32. {
  33. m_EventSystems.RemoveAt(index);
  34. m_EventSystems.Insert(0, value);
  35. }
  36. else if (index < 0)
  37. {
  38. Debug.LogError("Failed setting EventSystem.current to unknown EventSystem " + value);
  39. }
  40. }
  41. }
  42. [SerializeField]
  43. [FormerlySerializedAs("m_Selected")]
  44. private GameObject m_FirstSelected;
  45. [SerializeField]
  46. private bool m_sendNavigationEvents = true;
  47. /// <summary>
  48. /// Should the EventSystem allow navigation events (move / submit / cancel).
  49. /// </summary>
  50. public bool sendNavigationEvents
  51. {
  52. get { return m_sendNavigationEvents; }
  53. set { m_sendNavigationEvents = value; }
  54. }
  55. [SerializeField]
  56. private int m_DragThreshold = 10;
  57. /// <summary>
  58. /// The soft area for dragging in pixels.
  59. /// </summary>
  60. public int pixelDragThreshold
  61. {
  62. get { return m_DragThreshold; }
  63. set { m_DragThreshold = value; }
  64. }
  65. private GameObject m_CurrentSelected;
  66. /// <summary>
  67. /// The currently active EventSystems.BaseInputModule.
  68. /// </summary>
  69. public BaseInputModule currentInputModule
  70. {
  71. get { return m_CurrentInputModule; }
  72. }
  73. /// <summary>
  74. /// Only one object can be selected at a time. Think: controller-selected button.
  75. /// </summary>
  76. public GameObject firstSelectedGameObject
  77. {
  78. get { return m_FirstSelected; }
  79. set { m_FirstSelected = value; }
  80. }
  81. /// <summary>
  82. /// The GameObject currently considered active by the EventSystem.
  83. /// </summary>
  84. public GameObject currentSelectedGameObject
  85. {
  86. get { return m_CurrentSelected; }
  87. }
  88. [Obsolete("lastSelectedGameObject is no longer supported")]
  89. public GameObject lastSelectedGameObject
  90. {
  91. get { return null; }
  92. }
  93. private bool m_HasFocus = true;
  94. /// <summary>
  95. /// Flag to say whether the EventSystem thinks it should be paused or not based upon focused state.
  96. /// </summary>
  97. /// <remarks>
  98. /// Used to determine inside the individual InputModules if the module should be ticked while the application doesnt have focus.
  99. /// </remarks>
  100. public bool isFocused
  101. {
  102. get { return m_HasFocus; }
  103. }
  104. protected EventSystem()
  105. {}
  106. /// <summary>
  107. /// Recalculate the internal list of BaseInputModules.
  108. /// </summary>
  109. public void UpdateModules()
  110. {
  111. GetComponents(m_SystemInputModules);
  112. var systemInputModulesCount = m_SystemInputModules.Count;
  113. for (int i = systemInputModulesCount - 1; i >= 0; i--)
  114. {
  115. if (m_SystemInputModules[i] && m_SystemInputModules[i].IsActive())
  116. continue;
  117. m_SystemInputModules.RemoveAt(i);
  118. }
  119. }
  120. private bool m_SelectionGuard;
  121. /// <summary>
  122. /// Returns true if the EventSystem is already in a SetSelectedGameObject.
  123. /// </summary>
  124. public bool alreadySelecting
  125. {
  126. get { return m_SelectionGuard; }
  127. }
  128. /// <summary>
  129. /// Set the object as selected. Will send an OnDeselect the the old selected object and OnSelect to the new selected object.
  130. /// </summary>
  131. /// <param name="selected">GameObject to select.</param>
  132. /// <param name="pointer">Associated EventData.</param>
  133. public void SetSelectedGameObject(GameObject selected, BaseEventData pointer)
  134. {
  135. if (m_SelectionGuard)
  136. {
  137. Debug.LogError("Attempting to select " + selected + "while already selecting an object.");
  138. return;
  139. }
  140. m_SelectionGuard = true;
  141. if (selected == m_CurrentSelected)
  142. {
  143. m_SelectionGuard = false;
  144. return;
  145. }
  146. // Debug.Log("Selection: new (" + selected + ") old (" + m_CurrentSelected + ")");
  147. ExecuteEvents.Execute(m_CurrentSelected, pointer, ExecuteEvents.deselectHandler);
  148. m_CurrentSelected = selected;
  149. ExecuteEvents.Execute(m_CurrentSelected, pointer, ExecuteEvents.selectHandler);
  150. m_SelectionGuard = false;
  151. }
  152. private BaseEventData m_DummyData;
  153. private BaseEventData baseEventDataCache
  154. {
  155. get
  156. {
  157. if (m_DummyData == null)
  158. m_DummyData = new BaseEventData(this);
  159. return m_DummyData;
  160. }
  161. }
  162. /// <summary>
  163. /// Set the object as selected. Will send an OnDeselect the the old selected object and OnSelect to the new selected object.
  164. /// </summary>
  165. /// <param name="selected">GameObject to select.</param>
  166. public void SetSelectedGameObject(GameObject selected)
  167. {
  168. SetSelectedGameObject(selected, baseEventDataCache);
  169. }
  170. private static int RaycastComparer(RaycastResult lhs, RaycastResult rhs)
  171. {
  172. if (lhs.module != rhs.module)
  173. {
  174. var lhsEventCamera = lhs.module.eventCamera;
  175. var rhsEventCamera = rhs.module.eventCamera;
  176. if (lhsEventCamera != null && rhsEventCamera != null && lhsEventCamera.depth != rhsEventCamera.depth)
  177. {
  178. // need to reverse the standard compareTo
  179. if (lhsEventCamera.depth < rhsEventCamera.depth)
  180. return 1;
  181. if (lhsEventCamera.depth == rhsEventCamera.depth)
  182. return 0;
  183. return -1;
  184. }
  185. if (lhs.module.sortOrderPriority != rhs.module.sortOrderPriority)
  186. return rhs.module.sortOrderPriority.CompareTo(lhs.module.sortOrderPriority);
  187. if (lhs.module.renderOrderPriority != rhs.module.renderOrderPriority)
  188. return rhs.module.renderOrderPriority.CompareTo(lhs.module.renderOrderPriority);
  189. }
  190. if (lhs.sortingLayer != rhs.sortingLayer)
  191. {
  192. // Uses the layer value to properly compare the relative order of the layers.
  193. var rid = SortingLayer.GetLayerValueFromID(rhs.sortingLayer);
  194. var lid = SortingLayer.GetLayerValueFromID(lhs.sortingLayer);
  195. return rid.CompareTo(lid);
  196. }
  197. if (lhs.sortingOrder != rhs.sortingOrder)
  198. return rhs.sortingOrder.CompareTo(lhs.sortingOrder);
  199. // comparing depth only makes sense if the two raycast results have the same root canvas (case 912396)
  200. if (lhs.depth != rhs.depth && lhs.module.rootRaycaster == rhs.module.rootRaycaster)
  201. return rhs.depth.CompareTo(lhs.depth);
  202. if (lhs.distance != rhs.distance)
  203. return lhs.distance.CompareTo(rhs.distance);
  204. return lhs.index.CompareTo(rhs.index);
  205. }
  206. private static readonly Comparison<RaycastResult> s_RaycastComparer = RaycastComparer;
  207. /// <summary>
  208. /// Raycast into the scene using all configured BaseRaycasters.
  209. /// </summary>
  210. /// <param name="eventData">Current pointer data.</param>
  211. /// <param name="raycastResults">List of 'hits' to populate.</param>
  212. public void RaycastAll(PointerEventData eventData, List<RaycastResult> raycastResults)
  213. {
  214. raycastResults.Clear();
  215. var modules = RaycasterManager.GetRaycasters();
  216. var modulesCount = modules.Count;
  217. for (int i = 0; i < modulesCount; ++i)
  218. {
  219. var module = modules[i];
  220. if (module == null || !module.IsActive())
  221. continue;
  222. module.Raycast(eventData, raycastResults);
  223. }
  224. raycastResults.Sort(s_RaycastComparer);
  225. }
  226. /// <summary>
  227. /// Is the pointer with the given ID over an EventSystem object?
  228. /// </summary>
  229. public bool IsPointerOverGameObject()
  230. {
  231. return IsPointerOverGameObject(PointerInputModule.kMouseLeftId);
  232. }
  233. /// <summary>
  234. /// Is the pointer with the given ID over an EventSystem object?
  235. /// </summary>
  236. /// <remarks>
  237. /// 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
  238. /// Note that for touch, IsPointerOverGameObject should be used with ''OnMouseDown()'' or ''Input.GetMouseButtonDown(0)'' or ''Input.GetTouch(0).phase == TouchPhase.Began''.
  239. /// </remarks>
  240. /// <example>
  241. /// <code>
  242. /// using UnityEngine;
  243. /// using System.Collections;
  244. /// using UnityEngine.EventSystems;
  245. ///
  246. /// public class MouseExample : MonoBehaviour
  247. /// {
  248. /// void Update()
  249. /// {
  250. /// // Check if the left mouse button was clicked
  251. /// if (Input.GetMouseButtonDown(0))
  252. /// {
  253. /// // Check if the mouse was clicked over a UI element
  254. /// if (EventSystem.current.IsPointerOverGameObject())
  255. /// {
  256. /// Debug.Log("Clicked on the UI");
  257. /// }
  258. /// }
  259. /// }
  260. /// }
  261. /// </code>
  262. /// </example>
  263. public bool IsPointerOverGameObject(int pointerId)
  264. {
  265. return m_CurrentInputModule != null && m_CurrentInputModule.IsPointerOverGameObject(pointerId);
  266. }
  267. protected override void OnEnable()
  268. {
  269. base.OnEnable();
  270. m_EventSystems.Add(this);
  271. }
  272. protected override void OnDisable()
  273. {
  274. if (m_CurrentInputModule != null)
  275. {
  276. m_CurrentInputModule.DeactivateModule();
  277. m_CurrentInputModule = null;
  278. }
  279. m_EventSystems.Remove(this);
  280. base.OnDisable();
  281. }
  282. private void TickModules()
  283. {
  284. var systemInputModulesCount = m_SystemInputModules.Count;
  285. for (var i = 0; i < systemInputModulesCount; i++)
  286. {
  287. if (m_SystemInputModules[i] != null)
  288. m_SystemInputModules[i].UpdateModule();
  289. }
  290. }
  291. protected virtual void OnApplicationFocus(bool hasFocus)
  292. {
  293. m_HasFocus = hasFocus;
  294. if (!m_HasFocus)
  295. TickModules();
  296. }
  297. protected virtual void Update()
  298. {
  299. if (current != this)
  300. return;
  301. TickModules();
  302. bool changedModule = false;
  303. var systemInputModulesCount = m_SystemInputModules.Count;
  304. for (var i = 0; i < systemInputModulesCount; i++)
  305. {
  306. var module = m_SystemInputModules[i];
  307. if (module.IsModuleSupported() && module.ShouldActivateModule())
  308. {
  309. if (m_CurrentInputModule != module)
  310. {
  311. ChangeEventModule(module);
  312. changedModule = true;
  313. }
  314. break;
  315. }
  316. }
  317. // no event module set... set the first valid one...
  318. if (m_CurrentInputModule == null)
  319. {
  320. for (var i = 0; i < systemInputModulesCount; i++)
  321. {
  322. var module = m_SystemInputModules[i];
  323. if (module.IsModuleSupported())
  324. {
  325. ChangeEventModule(module);
  326. changedModule = true;
  327. break;
  328. }
  329. }
  330. }
  331. if (!changedModule && m_CurrentInputModule != null)
  332. m_CurrentInputModule.Process();
  333. #if UNITY_EDITOR
  334. if (Application.isPlaying)
  335. {
  336. int eventSystemCount = 0;
  337. for (int i = 0; i < m_EventSystems.Count; i++)
  338. {
  339. if (m_EventSystems[i].GetType() == typeof(EventSystem))
  340. eventSystemCount++;
  341. }
  342. if (eventSystemCount > 1)
  343. Debug.LogWarning("There are " + eventSystemCount + " event systems in the scene. Please ensure there is always exactly one event system in the scene");
  344. }
  345. #endif
  346. }
  347. private void ChangeEventModule(BaseInputModule module)
  348. {
  349. if (m_CurrentInputModule == module)
  350. return;
  351. if (m_CurrentInputModule != null)
  352. m_CurrentInputModule.DeactivateModule();
  353. if (module != null)
  354. module.ActivateModule();
  355. m_CurrentInputModule = module;
  356. }
  357. public override string ToString()
  358. {
  359. var sb = new StringBuilder();
  360. sb.AppendLine("<b>Selected:</b>" + currentSelectedGameObject);
  361. sb.AppendLine();
  362. sb.AppendLine();
  363. sb.AppendLine(m_CurrentInputModule != null ? m_CurrentInputModule.ToString() : "No module");
  364. return sb.ToString();
  365. }
  366. }
  367. }