SelectOnInput.cs (2635B)
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 using UnityEngine.EventSystems; 5 6 public class SelectOnInput : MonoBehaviour 7 { 8 public EventSystem eventSystem; 9 public List<GameObject> selectableObjects; 10 11 private bool buttonSelected = false; 12 private int cursorPosition = 0; 13 private bool lastState; 14 // Start is called before the first frame update 15 void Start() 16 { 17 18 } 19 20 // Update is called once per frame 21 void Update() 22 { 23 if (Input.GetAxisRaw("GlobalHorizontal") != 0) 24 { 25 // Debug.Log(Input.GetAxis("GlobalHorizontal")); 26 } 27 28 if ((Input.GetAxisRaw("Horizontal") < -0.1 || Input.GetAxis("GlobalHorizontal") < -0.1) && !buttonSelected) 29 { 30 Debug.Log("Left"); 31 cursorPosition++; 32 if (cursorPosition > selectableObjects.Count - 1) 33 { 34 cursorPosition = 0; 35 } 36 37 eventSystem.SetSelectedGameObject(selectableObjects[cursorPosition].gameObject); 38 39 buttonSelected = true; 40 41 //GameObject Selected = selectableObjects[cursorPosition].gameObject; 42 //ExecuteEvents.Execute<ISelectHandler>(Selected, new BaseEventData(EventSystem.current), ExecuteEvents.selectHandler); 43 44 //buttonSelected = true; 45 } 46 47 if ((Input.GetAxisRaw("Horizontal") > 0.1) && !buttonSelected) 48 { 49 Debug.Log("Right"); 50 cursorPosition--; 51 if (cursorPosition < 0) 52 { 53 cursorPosition = 0; 54 } 55 56 eventSystem.SetSelectedGameObject(selectableObjects[cursorPosition].gameObject); 57 58 buttonSelected = true; 59 //GameObject Selected = selectableObjects[cursorPosition].gameObject; 60 //ExecuteEvents.Execute<ISelectHandler>(Selected, new BaseEventData(EventSystem.current), ExecuteEvents.selectHandler); 61 62 //buttonSelected = true; 63 } 64 65 if ((Input.GetButtonUp("Horizontal") || LikeOnKeyDown("GlobalHorizontal")) && buttonSelected) 66 { 67 buttonSelected = false; 68 } 69 } 70 71 private bool LikeOnKeyDown(string axis) 72 { 73 //Converts axis input to just true/false like button press 74 var currentState = Input.GetAxisRaw(axis) > 0.1; 75 if (currentState && lastState) 76 { 77 return false; 78 } 79 80 lastState = currentState; 81 //buttonSelected = false; 82 return currentState; 83 } 84 85 private void OnDisable() 86 { 87 buttonSelected = false; 88 } 89 }