With NGUI, buttons are easy to create and configure.
Let's create our first one by performing the following steps:
Buttons
. It will be our buttons container.A button has just been created and centered on the screen. If you look at the Hierarchy view, you will see that a button is composed of a container GameObject named Button and two children: a Background sprite and Label. That's how NGUI works; templates are simply assembled components and widgets. If you wanted to, you could build a button from scratch using the right components on empty GameObjects.
Click on the Play button. You can see that hover and click are already set! Turn off the Play mode, select the new Button GameObject, and look at the Inspector view.
Interactive widgets have a box collider attached to them, and that is the case with this button. The collider is used to detect collisions with the cursor.
A button has a UIButton
component that handles seven button parameters:
In the previous example, I dragged the Panel GameObject into the Notify field. My Panel GameObject has a ButtonManager.cs
script attached to it—this script has a ButtonClicked()
method. I can now select it in the Method field. It will be called on click.
There is also a PlaySound component attached to this button. It lets you choose an audio clip to play when the selected event occurs. You can edit the Pitch and Volume parameters.
We will now add two buttons to our window that will exit or launch the game. They will appear as shown in the following screenshot:
We need a GameObject that will manage the game. It will contain the GameManager.cs
script attached in order to manage generic behaviors such as exiting or launching the game. Let's create it first; follow these steps to do so:
GameManager
.GameManager.cs
C# script to it and perform the following steps:GameManager.cs
script.ExitPressed()
with the following code lines:public void ExitPressed() { //Exit Now Application.Quit(); }
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Now that the exit method is ready, let's create and configure the two buttons as shown in the following steps:
Exit
.185
, G to 255
, B to 255
, and A to 255
.0
, G to 220
, B to 255
, and A to 255
.135
, 60
}.2
.Exit
.3
.Ok, we have our Exit button. Let's create our Play button as follows:
Play
.-135
, 60
}.Play
.Perfect, now if you build your scene, you will have a functional Exit button with only one line of code! The Pixel Offset parameter maintains our buttons at the same distance from the window's borders even if you change resolutions or the window's dimensions. We will create our game scene later.
18.189.189.67