Saturday, 30 August 2014

[JavaScript] GUI Buttons

JavaScript Tutorial

Today we are going to be looking at GUI Buttons.

What is a GUI Button?
A GUI Button is a button that appears on the screen when you put a position and text box in, don't forget to include the size.

Where does a GUI button have to be?
GUI buttons need to be inside function OnGUI() for it to work.

An example of a GUI button:
GUI.Button (Rect (0, 0, 262, 20), "I am a button!");
This a GUI button that appears in the top left of the screen that sais "I am a button!"

Variables with GUI Buttons:
This is also a very good way of using buttons, let's say we want to display an amount of cash to buy something with our button, it will appear.
var price : float = 10f;

function OnGUI() {

    GUI.Button (Rect (0, 0, 262, 20), "Buy me for $" + price);
}

Now it should appear as "Buy me for $10!" in a button, but you notice you cannot click on it. We will get into that next.

Making buttons do things:
To make buttons do things, we need to add an if() { to the button, here's an example:
if(GUI.Button (Rect (0, 0, 262, 20), "Buy me for $" + price)) {
  // place stuff here
}

Now if we click on it, nothing will happen, let's change it to something where it loads a level:

if(GUI.Button (Rect (0, 0, 262, 20), "Buy me for $" + price)) {
  Application.LoadLevel("LEVELNAMEHERE"); /* loads the level names "LEVELNAMEHERE" */
}

Now if you have a level called LEVELNAMEHERE on your game, it will load that level.

That's it for this java tutorial, bye!

No comments:

Post a Comment