Unity – Scripting – OnGUI – Buttons
Videogames Development – Unity – Code GUI Objects – Buttons
UnityGUI allows you to create a wide variety of highly functional GUIs very quickly and easily. Rather than creating a GUI object, manually positioning it, and then writing a script that handles its functionality, you can do everything at once with just a few lines of code. The code produces GUI controls that are instantiated, positioned and handled with a single function call.
Simple Text Button
1. Assign the script to the Camera:
#pragma strict function Start () { } function OnGUI () { if (GUI.Button (Rect (10,10,150,100), "I am a button")) { print ("You clicked the button!"); } } function Update () { }
Statement:
GUI.Button (Rect (10,10,150,100), “I am a button”)
GUI.Button (Rectangular (x topleft,y topleft,x bottomright,y bottomright), “Button Text”)
Image Button
1. Assign the script to the Camera:
#pragma strict var btnTexture : Texture; function OnGUI() { // Texture Controller if (!btnTexture) { Debug.LogError("Please assign a texture on the inspector"); return; } if (GUI.Button(Rect(10,10,150,100),btnTexture)) Debug.Log("Clicked the button with an image"); }
2. Select the Camera> ‘Inspector’> Script> DRAG AND DROP Texture from ‘Assets’ to Script> ‘Btn Texture’ variable.
3. Play and enjoy!
Multiple Buttons
1. Assign the script to the Camera:
Left Side Bar:
#pragma strict function OnGUI() { // Multiple Buttons - Left Side Bar if (GUI.Button(Rect(10,10,50,50),"BTN1")) Debug.Log("Clicked BTN1"); if (GUI.Button(Rect(10,70,50,50),"BTN2")) Debug.Log("Clicked BTN2"); if (GUI.Button(Rect(10,130,50,50),"BTN3")) Debug.Log("Clicked BTN3"); if (GUI.Button(Rect(10,190,50,50),"BTN4")) Debug.Log("Clicked BTN4"); }
Top Left Bar:
#pragma strict function OnGUI() { // Multiple Buttons - Top Left Bar if (GUI.Button(Rect(10,10,50,50),"BTN1")) Debug.Log("Clicked BTN1"); if (GUI.Button(Rect(70,10,50,50),"BTN2")) Debug.Log("Clicked BTN2"); if (GUI.Button(Rect(130,10,50,50),"BTN3")) Debug.Log("Clicked BTN3"); if (GUI.Button(Rect(190,10,50,50),"BTN4")) Debug.Log("Clicked BTN4"); }