The Graphical User Interface, otherwise known as GUI, is one of the ways we get and give information to the player. This includes things like: text, input boxes, buttons, labels, windows, scroll bars, and many more.
All GUI Instructions are handled by a built in Unity function called OnGUI.
OnGUI runs twice per frame. The first time it runs it is looking for input (mouse click, keyboard, etc…). The second time it runs it is updating the graphical output and resolving input.
function OnGUI( )
GUI Instructions here.
There are many different GUI items that we can use. These can be found in the Scripting Reference Guide and in the Users Guide. We are going to look at labels, textfields, and buttons in this post.
A label is just text that you want to display in your game.
Here is how you make a label:
GUI.Label(Rect(10,20,100,20), “This is a Label.”);
This has to be typed into the OnGUI function. First you tell the computer you want a label by typing “GUI.Label”. Then you need to define a rectangle for the label by using the Rect command. In the parenthesis you put four numbers. The first number is the location of the top left corner of the rectangle on the x axis. Unity starts with x equal to 0 on the left edge of the screen. The next number is the location of the top left corner of the rectangle on the y axis. Unity starts with y = 0 at the top of the screen. So the coordinates 0,0 are at the top left corner of the screen. The next (third) number is the width of the rectangle. The forth number is the height of the rectangle.
In our example above the rectangle for our label would be located with its top left corner at 10x, 20y, width100, height20. This would make a label at the top left of the screen. For a good explanation and examples of this click here.
After the rectangle you put the text you want the player to see in quotes. Our example above would display “This is a Label.” to the player.
To make a clickable button we add the following code to our OnGUI function:
Do instructions if button is clicked;
We need to do this inside an if statement because a button returns a true when it is clicked and a false if it is not clicked. If it is clicked the if statement will run it’s code to do whatever we wanted the button to do.
Again we need to define a rectangle to position and size the button. The button above would be located at 150x, 150y and be 90 pixels wide and 45 pixels high. The words on the button in our example would be “Click Me”.
For more on buttons click here.
To make an area where the player can enter text you add a TextField control.
You would first make a String variable to hold the information.
var textFieldString:String = “Type Here”;
Then in your OnGUI function you would type this:
textFieldString = GUI.TextField (Rect (25, 25, 100, 30), textFieldString);
This will display the current text stored in the textFieldString and overwrite it with the new text entered by the player.
For more on GUI TextFields and controls click here.