Game Development Reference
In-Depth Information
In this example, we draw a box, a text field, and a password field together with a
simple button within a group, which is then centered on the screen.
We check whether the user hits the
Enter
key and whether they are on the password
field (checked using the
GUI.GetNameOfFocusedControl()
function) and we try to
register them. The same happens if the user clicks on the
Register
button.
If the user's password is longer than six characters, then they are registered; if not,
then the
passwordInError
flag is set to
True
, which causes the additional label to
be drawn, this then warns the user that their password could be broken easily by
a 6-year-old.
Don't forget to add the
IntermediateGUI
script to an active
GameObject in a scene or
Main Camera
to see the result!
Tooltips
Each of the GUI controls can also have a tooltip associated with it to display some
additional text when it is either in focus or the mouse is hovering over the control.
Adding a tooltip is simple; you just need to replace the content of the control when it
is being drawn using the
GUIContent
class. For example, we can update the
Register
button in the previous script as follows:
if (GUI.Button(new Rect(80, 130, 65, 20),
new GUIContent("Register", "My Tooltip")))
{
CheckUserPasswordAndRegister();
}
With the tooltip defined, we just then need to display the current tooltip somewhere
on the screen, usually as a label, but it can be any control that can display text (input
fields are not recommended however), so add the following after the button block
but before
EndGroup()
:
GUI.Label (new Rect (10, 120, 65, 20), GUI.tooltip);
This simply gets the content of the current tooltip in focus and returns the tooltip text
for that control.
GUIContent
also has several other options for displaying text and
texture variants, so it's worth checking out some more.