Time for action – create a button UI control
We're going to add a button to the title screen through code, using Unity's built-in OnGUI
function:
Double-click on the TitleGUI script, or switch over to the script editor if it's already open.
We won't need the
Update
function any longer. Instead, we'll be using the built-inOnGUI
function. Change the wordUpdate
toOnGUI
:var customSkin:GUISkin; function OnGUI() { }
Add a chunk of code that creates a button inside the
OnGUI
function:var customSkin:GUISkin; function OnGUI() { if(GUI.Button(Rect(0,0,100,50),"Play Game")) { print("You clicked me!"); } }
Save the script and press the Unity Play button to test your game.
A button labeled Play Game appears at the top-left of the screen. When you click on it, the message You clicked me! appears in the status bar at the bottom of the Unity interface. It will also appear in the Console window if you have it open.
Great! With a very tiny bit of code, we have a working, labeled button up on the screen...