Game Development Reference
In-Depth Information
In MonoDevelop, edit the GUIButtons script code to the following:
function OnGUI () {
if (GUI.Button (Rect (25, 260, 100, 30), "Click Me")) {
Debug.Log("Button has been clicked");
}
if (GUI.RepeatButton (Rect (25, 300, 100, 30), "Click and Hold")) {
Debug.Log("The repeat button is being pressed");
}
}
Save the script and playtest. Compare the action of the two buttons and notice that the repeat button's
Debug.Log statement is printed to the Console every frame as long as the repeat button is held.
Screen
The left side of the Game view is getting crowded with controls, so before adding more controls, you
will move the buttons to the right side. Unity provides you with a handy Screen class that can provide
you with information such as screen resolution and size, or whether the mouse cursor is shown or
hidden. In this example you will use the Screen.width and Screen.height variables to help with GUI
control placement.
To move the button to the upper right corner, edit its position in the GUIButtons script to the following:
if (GUI.Button (Rect (Screen.width - 100, 0, 100, 30), "Click Me")) {
Since the button position coordinates coincide with its upper left corner, you have to subtract the width
of the button. Otherwise, its left side would begin on the last pixel of the right side of the screen.
Move the repeat button beneath it by editing its position in the GUIButtons script to the following:
if (GUI.RepeatButton (Rect (Screen.width - 100, 50, 100, 30), "Click and Hold")) {
Save the scene and playtest to see the new button positions.
Likewise you can reposition the player instructions in the label to the center of the screen by editing
its code in the GUIScript script as follows:
GUI.Label(Rect(Screen.width/2, Screen.height/2, 250, 25), "Press C to crouch or Space to jump");
If you save and playtest now, the label will appear too low and too far to the right. This is again because
the upper left corner of the label is what is positioned at the ( Screen.width/2 , Screen.height/2 )
coordinates. You can manage this as you did the buttons, but to maintain centering this time, subtract
half the respective width and height of the label. The line of code should now look like this:
GUI.Label(Rect(Screen.width/2 - 125, Screen.height/2 - 12.5, 250, 25), "Press C to crouch or Space
to jump");
Save the script, save the scene, and playtest to see the fading message appear in the center of
the screen.
 
Search WWH ::




Custom Search