|
| 1 | +using System.Collections.Generic; |
| 2 | +using UnityEngine; |
| 3 | +using UnityEngine.EventSystems; |
| 4 | +using UnityEngine.InputSystem; |
| 5 | + |
| 6 | +namespace Zigurous.UI |
| 7 | +{ |
| 8 | + [RequireComponent(typeof(EventSystem))] |
| 9 | + [AddComponentMenu("Zigurous/UI/Navigation/Navigation Stack")] |
| 10 | + public class NavigationStack : MonoBehaviour |
| 11 | + { |
| 12 | + public EventSystem eventSystem { get; private set; } |
| 13 | + public Stack<GameObject> navigationStack { get; private set; } |
| 14 | + public GameObject CurrentSelectedGameObject => this.navigationStack.Peek(); |
| 15 | + public InputAction backInput; |
| 16 | + public bool allowEmptyStack = false; |
| 17 | + public bool allowNullSelections = false; |
| 18 | + |
| 19 | + private void Reset() |
| 20 | + { |
| 21 | + this.backInput = new InputAction("MenuBackNavigation", InputActionType.Button); |
| 22 | + this.backInput.AddBinding("<Keyboard>/escape"); |
| 23 | + this.backInput.AddBinding("<Keyboard>/backspace"); |
| 24 | + this.backInput.AddBinding("<Gamepad>/select"); |
| 25 | + this.backInput.AddBinding("<Gamepad>/buttonEast"); |
| 26 | + } |
| 27 | + |
| 28 | + private void Awake() |
| 29 | + { |
| 30 | + this.eventSystem = GetComponent<EventSystem>(); |
| 31 | + this.navigationStack = new Stack<GameObject>(8); |
| 32 | + } |
| 33 | + |
| 34 | + private void OnEnable() |
| 35 | + { |
| 36 | + this.backInput.Enable(); |
| 37 | + this.backInput.performed += OnBack; |
| 38 | + } |
| 39 | + |
| 40 | + private void OnDisable() |
| 41 | + { |
| 42 | + this.backInput.Disable(); |
| 43 | + this.backInput.performed -= OnBack; |
| 44 | + } |
| 45 | + |
| 46 | + private void Update() |
| 47 | + { |
| 48 | + if (this.eventSystem.currentSelectedGameObject != CurrentSelectedGameObject) |
| 49 | + { |
| 50 | + if (this.eventSystem.currentSelectedGameObject != null || this.allowNullSelections) { |
| 51 | + this.navigationStack.Push(this.eventSystem.currentSelectedGameObject); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + public void Back() |
| 57 | + { |
| 58 | + if (this.navigationStack.Count == 0) { |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + if (this.navigationStack.Count > 1 || this.allowEmptyStack) { |
| 63 | + this.navigationStack.Pop(); |
| 64 | + } |
| 65 | + |
| 66 | + this.eventSystem.SetSelectedGameObject(null); |
| 67 | + |
| 68 | + if (this.navigationStack.Count > 0) { |
| 69 | + this.eventSystem.SetSelectedGameObject(this.navigationStack.Peek()); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + private void OnBack(InputAction.CallbackContext context) |
| 74 | + { |
| 75 | + if (context.performed) { |
| 76 | + Back(); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + } |
| 81 | + |
| 82 | +} |
0 commit comments