Game Development Reference
In-Depth Information
More Controls
Many of the common interactive elements are available as GUI controls, including buttons, toggles,
and sliders. When creating any of the GUI controls you will notice they all follow the pattern of
position-size-content.
Button
The basic button responds once when clicked, at the release of the mouse button. It returns true
when clicked and otherwise false . In your script, you use a conditional to test for the true state; it
then executes its block of code when the button is clicked.
In the Project panel Assets ➤ Scripts folder, create a new script named GUIButtons. Open it in
MonoDevelop and edit the code to the following:
#pragma strict
function OnGUI () {
if (GUI.Button (Rect (25, 260, 100, 30), "Click Me")) {
Debug.Log("Button has been clicked");
}
}
This code breaks down as follows:
(1) if (GUI.Button (Rect (25, 260, 100, 30), "Click Me"))
1.
This efficient line of code creates the GUI button and tests its state at the
same time.
(2) Debug.Log("Button has been clicked");
If the button state returns true , meaning it has been clicked, the Debug.Log
statement will appear in the Console.
2.
Save the script, attach it to the GUI game object, and playtest. Click the button to confirm
“Button has been clicked” appears in the Console.
You could put any kind of code into this conditional statement. Since you already know how to write
code that affects the game object to which the script is attached and any other game object in the
scene, your code here can affect any game object behavior. Save the scene and the project.
Repeat Button
The repeat button differs from the button in that it returns true every frame as long as the repeat
button is pressed.
 
Search WWH ::




Custom Search