Unity3D doesn’t support controling GUI elements with keyboard by default – only with mouse. We can program this with use of GUI.SetNextControlName and GUI.FocusControl
First we need to declare array, where we will store our button names and index of currently selected.
string[] buttons = new string[3] {"Start", "Options", "Exit" }; int selected = 0;
Then in OnGUI we set name for Next GUI element which is the button – this is for control the GUI focus, which we are doing with GUI.FocusControl on currently selected button.
void OnGUI(){ GUI.SetNextControlName(buttons[0]); If(GUI.Button(new Rect(0,0,100,100), buttons[0]){ //when selected Start button } GUI.SetNextControlName(buttons[1]); If(GUI.Button(new Rect(0,100,100,100), buttons[1]){ //when selected Options button } GUI.SetNextControlName(buttons[2]); If(GUI.Button(new Rect(0,200,100,100), buttons[2]){ //when selected Exit button } GUI.FocusControl(buttons[selected]); }
Then in Start function make current selection defaultly to first button.
void Start(){ selected = 0; }
Then we need to control the selected index based on our input. Lets write little function to help us.
int menuSelection (string[] buttonsArray, int selectedItem, string direction) { if (direction == "up") { if (selectedItem == 0) { selectedItem = buttonsArray.length - 1; } else { selectedItem -= 1; } } if (direction == "down") { if (selectedItem == buttonsArray.length - 1) { selectedItem = 0; } else { selectedItem += 1; } } return selectedItem; }
Then we will call it inside Update and some if statements, based on our input.
void Update(){ if(Input.GetKeyDown(KeyCode.W)){ selected = menuSelection(buttons, selected, "up"); } if(Input.GetKeyDown(KeyCode.S)){ selected = menuSelection(buttons, selected, "down"); } }
And this is it! You can check the complete code below.
string[] buttons = new string[3] {"Start", "Options", "Exit" }; int selected = 0; void Start(){ selected = 0; } int menuSelection (string[] buttonsArray, int selectedItem, string direction) { if (direction == "up") { if (selectedItem == 0) { selectedItem = buttonsArray.length - 1; } else { selectedItem -= 1; } } if (direction == "down") { if (selectedItem == buttonsArray.length - 1) { selectedItem = 0; } else { selectedItem += 1; } } return selectedItem; } void Update(){ if(Input.GetKeyDown(KeyCode.W)){ selected = menuSelection(buttons, selected, "up"); } if(Input.GetKeyDown(KeyCode.S)){ selected = menuSelection(buttons, selected, "down"); } } void OnGUI(){ GUI.SetNextControlName(buttons[0]); If(GUI.Button(new Rect(0,0,100,100), buttons[0]){ //when selected Start button } GUI.SetNextControlName(buttons[1]); If(GUI.Button(new Rect(0,100,100,100), buttons[1]){ //when selected Options button } GUI.SetNextControlName(buttons[2]); If(GUI.Button(new Rect(0,200,100,100), buttons[2]){ //when selected Exit button } GUI.FocusControl(buttons[selected]); }
Hope you guys enjoyed this tutorial and write me your thought down below!