KeyBoardNavigation.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class KeyBoardNavigation : MonoBehaviour
  6. {
  7. public static HashSet<KeyBoardNavigation> NavigationSet = new();
  8. public List<Button> buttons;
  9. public static bool IsNavigationButton(Button btn)
  10. {
  11. foreach (var item in NavigationSet)
  12. {
  13. if (item.buttons.Contains(btn)) return true;
  14. }
  15. return false;
  16. }
  17. public static Button Next(Button btn, int delta, bool first = false)
  18. {
  19. if (Mathf.Abs(delta) != 1) throw new System.Exception("delta only support 1 or -1");
  20. List<Button> buttons = btn.GetComponentInParent<KeyBoardNavigation>().buttons;
  21. if (buttons.Count == 0) throw new System.Exception("KeyBoardNavigation.buttons Is Empty");
  22. int index = first ? (delta < 0 ? buttons.Count : -1) : buttons.IndexOf(btn);
  23. if (delta < 0 && index < 0) index = buttons.Count;
  24. int maxCheckCount = buttons.Count;
  25. for (int i = 0; i < maxCheckCount; i++)
  26. {
  27. index += delta;
  28. if (index < 0) index += buttons.Count;
  29. index = index % buttons.Count;
  30. Button curBtn = buttons[index];
  31. if (curBtn && curBtn.gameObject && curBtn.gameObject.activeInHierarchy && curBtn.interactable)
  32. {
  33. return buttons[index];
  34. }
  35. }
  36. return null;
  37. }
  38. void Awake()
  39. {
  40. if (!CommonConfig.StandaloneMode)
  41. {
  42. Destroy(this);
  43. }
  44. }
  45. void OnEnable()
  46. {
  47. NavigationSet.Add(this);
  48. }
  49. void OnDisable()
  50. {
  51. if (NavigationSet.Contains(this))
  52. {
  53. NavigationSet.Remove(this);
  54. }
  55. }
  56. }