Adding function to my Menu Script

Hi all,

After some serious research I’ve created this simple menu script. It uses a GuiSkin and displays 3 buttons on the screen. I can use the Up and Down arrows to move between the buttons which highlight and when i hit space the console displays a message. So far so good.

My question would be how do i go about adding a load level function to each button so that when i move the Up down keys to choose which option i want and hit space it would load the appropriate level. I don’t want to use the mouse as once this is working i can then add support for my Ouya controller.

heres my script so far…

var guiSkin : GUISkin;
var selectAudio : AudioClip;


enum CurrentFocus {button1=1, button2=2, button3=3}
private var currentFocus : CurrentFocus = CurrentFocus.button1;

function Awake () {
	Screen.lockCursor = true;
}

function Update () {
	if (Input.GetKeyDown(KeyCode.Space)) {
		Debug.Log("hello world");
	}
	
	if ( (Input.GetKeyDown(KeyCode.UpArrow)) || (Input.GetKeyDown(KeyCode.DownArrow)) ) {
		audio.Play();	
	}

	switch (currentFocus) {
		case 1:
			if (Input.GetKeyDown(KeyCode.DownArrow)) {
				currentFocus = 2;
			} else if (Input.GetKeyDown(KeyCode.UpArrow)) {
				currentFocus = 1;
			}
			break;
		case 2:
			if (Input.GetKeyDown(KeyCode.DownArrow)) {
				currentFocus = 3;
			} else if (Input.GetKeyDown(KeyCode.UpArrow)) {
				currentFocus = 1;
			}
			break;
		case 3:
			if (Input.GetKeyDown(KeyCode.DownArrow)) {
				currentFocus = 3;
			} else if (Input.GetKeyDown(KeyCode.UpArrow)) {
				currentFocus = 2;
			}
			break;
	}


}

function OnGUI() {
	GUI.skin = guiSkin;
	
	GUI.SetNextControlName("1");
	GUI.Button(Rect(700,450,225,150), "", "button1");
	GUI.SetNextControlName("2");
	GUI.Button(Rect(700,575,225,150), "", "button2");
	GUI.SetNextControlName("3");
	GUI.Button(Rect(700,700,225,150), "", "button3");
	
	
	switch (currentFocus) {
		case 1:
			GUI.FocusControl("1");
			break;
		case 2:
			GUI.FocusControl("2");
			break;
		case 3:
			GUI.FocusControl("3");
			break;
			
	}
	
}

As always, many thanks in advance

Your buttons need to be inside of if statements.if(GUI.Button(Rect(700,450,225,150), "", "button1")){} Inside of the if statement, use the built in function Application.LoadLevel. Use this as a reference: Unity - Scripting API: Application.LoadLevel

You could create an array of 3 states, simple integer, or maybe use switch and case, there are many possibilities. Here’s a simple solution.

var state : int = 0;

function Update(){

    //You can highlight gui button according to state.

    if (Input.GetKeyDown(KeyCode.DownArrow)){
        state++;
        if(state > 2) state = 2;
    }

    if (Input.GetKeyDown(KeyCode.UpArrow)){
        state--;
        if(state < 0) state = 0;
    }

    //on enter{
         if(state == 0)Application.LoadLevel("lvl1");
         else if(state == 1)Application.LoadLevel("lvl2");
         else if(state == 2)Application.LoadLevel("lvl3");
    }
}