Space bar selecting gui... not sure why

This is a simple little thing I wrote this morning that is a keypad controlled menu, and it works exactly how i’d like it to,
although I haven’t declared (that I know of) to use the space bar to select the gui… I’m not sure where i’d change this, cause i’d rather it be something I’ve declared so later on I can use a joystick or something.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class testscript : MonoBehaviour {

	public List<string> myMenuList = new List<string>();

	int selectedID = 0; 
	
		void OnGUI (){
			
			GUI.SetNextControlName ("Main Menu");
			if (GUI.Button(new Rect(10,70,100,25), "Main Menu")) {
			print ("Main Menu pressed");
			}
			
			GUI.SetNextControlName ("Play");	
			if (GUI.Button(new Rect(10,100,100,25), "Play")) {
			print ("Play button pressed");
			}
			
			GUI.SetNextControlName ("Exit");
			if (GUI.Button(new Rect(10,130,100,25), "Exit")) {
			print ("Exit button pressed");
			}

			GUI.FocusControl (myMenuList[selectedID]);

	}
	
	void Update () {

		   if(Input.GetKeyDown (KeyCode.UpArrow)){
			if(selectedID == 0){
				selectedID = myMenuList.Count - 1;
			} else { 
				selectedID -= 1;
			} 
		}

		if(Input.GetKeyDown (KeyCode.DownArrow)){
			if(selectedID == myMenuList.Count - 1){
				selectedID = 0;
			} else {
			selectedID += 1;
			}
		} 
	}
	
}

1 Answer

1

If you have a focussed button then Space presses it. I believe you have to swallow the space bar to stop it happening.

   if((Event.current.type == EventType.keyDown || Event.current.type == EventType.keyUp) && Event.current.keyCode == KeyCode.Space) {
       Event.current.Use();
   }

My that wasn't as simple a fix as I was hoping, back to the docs it is! Cheers for the quick reply!

–