Guest User

Untitled

a guest
Apr 19th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.EventSystems;
  4.  
  5. /// <summary>
  6. /// Allows moving between UI components using tab and shift-tab.
  7. /// </summary>
  8. public class TabNavigator : MonoBehaviour
  9. {
  10. EventSystem system;
  11.  
  12. bool isShiftHeld
  13. {
  14. get { return Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); }
  15. }
  16.  
  17. void Start()
  18. {
  19. system = EventSystem.current;
  20. }
  21.  
  22. void Update()
  23. {
  24. if (Input.GetKeyDown(KeyCode.Tab))
  25. {
  26. FocusNextSelectable();
  27. }
  28. }
  29.  
  30. void FocusNextSelectable()
  31. {
  32. var nextSelectable = GetNextSelectable();
  33.  
  34. if (!nextSelectable)
  35. {
  36. return;
  37. }
  38.  
  39. SimulateClick(nextSelectable);
  40. system.SetSelectedGameObject(nextSelectable.gameObject);
  41. }
  42.  
  43. Selectable GetNextSelectable()
  44. {
  45. if (!system.currentSelectedGameObject)
  46. {
  47. return null;
  48. }
  49.  
  50. var currentSelectable = system.currentSelectedGameObject.GetComponent<Selectable>();
  51.  
  52. if (!currentSelectable)
  53. {
  54. return null;
  55. }
  56.  
  57. return isShiftHeld ?
  58. currentSelectable.FindSelectableOnUp() :
  59. currentSelectable.FindSelectableOnDown();
  60. }
  61.  
  62. void SimulateClick(Selectable selectable)
  63. {
  64. var clickableElement = selectable.GetComponent<IPointerClickHandler>();
  65.  
  66. if (clickableElement == null)
  67. {
  68. return;
  69. }
  70.  
  71. var eventData = new PointerEventData(system);
  72. clickableElement.OnPointerClick(eventData);
  73. }
  74. }
Add Comment
Please, Sign In to add comment