Time for action – Creating a button UI control

We're going to add a button to the title screen through code, using Unity's built-in OnGUI function.

  1. Double-click on the TitleGUI script, or switch over to the script editor if it's already open.
  2. We won't need the Update function any longer. Instead, we'll be using the built-in OnGUI function. Change the word Update to OnGUI:
    var customSkin:GUISkin;
    function OnGUI() {
    }
  3. Add a button-creating a chunk of code inside the OnGUI function:
    var customSkin:GUISkin;
    function OnGUI() {
      if(GUI.Button(Rect(0,0,100,50),"Play Game"))  {
        print("You clicked me!");
      }
    }
  4. Save the script and click on 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 ...

Get Unity 3.x Game Development by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.