Tag Archives: user

Adding a UI to display the score in a 2D game with Unity

This tutorial continues on from the previous tutorial on adding collectables and scoring to a 2D Unity game. In the previous tutorial, we improved the points scoring system and added collectables (coins) of different values).

In this tutorial we will add a UI (user interface) which will display the number of coins collected to the user. The LevelManager script will be responsible for displaying and updating the score text on screen. Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the LevelManager script.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LevelManager : MonoBehaviour {
  public float respawnDelay;
  public PlayerController gamePlayer;
  public int coins;
  public Text coinText;

  // Use this for initialization
  void Start () {
    gamePlayer = FindObjectOfType<PlayerController> ();
    coinText.text = "Coins: " + coins;
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  public void Respawn(){
    StartCoroutine ("RespawnCoroutine");
  }

  public IEnumerator RespawnCoroutine(){
    gamePlayer.gameObject.SetActive (false);
    yield return new WaitForSeconds (respawnDelay);
    gamePlayer.transform.position = gamePlayer.respawnPoint;
    gamePlayer.gameObject.SetActive (true);
  }

  public void AddCoins(int numberOfCoins){
    coins += numberOfCoins;
    coinText.text = "Coins: " + coins;
  }
}

Handling form data with PHP

In this tutorial you will finally get to work with real user input through the use of forms and PHP code. This tutorial will show you how to create a simple PHP form which will ask for the user’s name and then display a simple message back to the user. This is what the form will look like:

Form with text box user input .
Form with text box user input .

The PHP code also includes some basic data validation that checks that the user has entered some value and asks them to enter their name if they haven’t.

Watch the video below and then scroll down to see the sample code.

Sample code

There are two files required – an HTML or PHP file which contains the form (eg. form.php), and a PHP file which handles the form data (eg. form_handler.php).

Step 1 – Create a form.php file and add the following code.

<html>
<head>
  <title>My form</title>
</head>

<body>
  <h3>Enter your name below:</h3>
  <form action="action_handler.php" method="GET">
    <p>Name: <input type="text" name="name"> <input type="submit"></p>
  </form>
</body>
</html>

Step 2 – Create an action_handler.php file and add the following code. The empty function is used to check if a text box has been left empty by the user (if they haven’t entered a value in the text box). Make sure both files are in the same folder/directory.

<?php
  $name = $_GET['name'];
  if(empty($name)){
    echo "You must enter your name.";
  }
  else{
    echo "Hello there, $name.";
  }
?>

That’s it. Now open the form.php file in your browser and try it out!

Graphical User Interfaces (GUIs)

A Graphical User Interface (GUI) provides a way for the game to provide information to the user or to read information from the user. This can be in the form of labels, buttons, text boxes, sliders, menus, and so on. The GUI can sit on top of the actual game. It is always a good idea to design your GUI before making the game – draw up a storyboard or wireframe with the types of GUI controls you want in the game and where you want to place them.

GUIs are created using code and can be added to any object or script in your game. If you have different parts of the GUI on different objects or scripts, it can become confusing and hard to maintain. It is a good idea to have all the GUI parts in one spot on one object.

In order to add a GUI to your scene, you need to add a special method to the script you have created for your GUI which is attached to an object in your scene eg. the camera. The special method that is used to create a GUI is called OnGUI(). This method takes no parameters and returns no data to whatever called it. The method will draw your GUI components on the screen and is called every single frame, just like the Update() method. Different GUI controls (eg. labels, buttons) will have code that goes inside the OnGUI() method.

Labels

Let’s start making a basic GUI that will draw a label with a short message on the screen. Labels display text on the screen that can be a simple string value, a variable value or a concatenated (joined) string and variable value eg. “Score: ” + scoreVariable.

A label displaying the score.
A label displaying the score.

Watch the video on Labels below or scroll down to read the instructions and sample code.

Create a new scene in your project and a new script called myGUI. Attach this script to the Main Camera. Add the following code to your script inside the class but outside of all other methods (i.e. do not place it inside the Start() or Update() methods).

void OnGUI(){
 GUI.Label (new Rect(0,0,80,20), "Hello");
}

Run the scene and you should see ‘Hello’ displayed on the screen in the top left corner. You have just created a basic GUI with a label that draws in the top left corner of your screen (at position 0 on x axis and position 0 on y axis of screen). The label has a width of 80 and a height of 20. The parameters inside Rect() are x position, y position, width, height. The label can display a string value or variable (or concatenated strings/variables).

Boxes

The box is similar to a label except that a box has a dark border around the label. An example of a box is shown below.

An example of a box.
An example of a box.

Watch the video on Boxes below or scroll down to read the instructions and sample code.

The syntax for creating a box is also similar to creating a label. new Rect() takes the parameters of x position, y position, width, and height). An example of a box containing a “Hello” string message is shown below. This code would be placed inside the OnGUI() method:

GUI.Box(new Rect(0,0,80,20), "Hello");

If you want a box at the middle-top area of the screen, you can use code like this. This code would be placed inside the OnGUI() method:

GUI.Box(new Rect(Screen.width / 2 - 20, 0, 80, 20), "Hello");

Buttons

Buttons can be in one of two states. A button can be either pressed down or not pressed down. An if statement can be used to determine whether a button is being pressed (a boolean value of true or false). If you keep the button pressed down with the mouse, it will not behave differently to just clicking once. The image below shows an example of a button.

An example of a button that reloads/resets the current level in a game.
An example of a button that reloads/resets the current level in a game.

Watch the video on Buttons below or scroll down to read the instructions and sample code.

Like labels and boxes, buttons require an x position, y position, a width and a height value. The sample code below shows how to create a button at an x position of 3, a y position of 3, with a width of 80 and height of 20. When the button is clicked it will reload the level (scene) using Application.LoadLevel. In this example the scene is called ‘myScene’. This code would be placed inside the OnGUI() method:

if (GUI.Button (new Rect (3, 3, 80, 20), "Reset")) {
 Application.LoadLevel ("myScene");
 }

Repeat button

A repeat button is like a normal button except that it can be pressed and held down with the mouse click. It can be used to increase the value of a variable while the button is being held down.

repeat_button

The example below increases a variable’s value while the button is being held down. This code would be placed inside the OnGUI() method:

if (GUI.RepeatButton (new Rect (0, 0, 80, 20), "Increase")) {
 myVariable += 1;
 print (myVariable);
 }

Toggle

A toggle button (also known as a ‘stated’ button because it can be in different states) is like a switch – it can be on or off. It can be used to set something in one state or another. It takes a boolean parameter (whether the button is clicked or not) and returns a boolean value (tells the user if the button is clicked).

The two images below show a toggle in two different states (off and on).

Screen Shot 2015-11-15 at 8.45.02 PM Screen Shot 2015-11-15 at 8.45.14 PM

An example of the code is shown below with a boolean variable called ‘mySwitch’.

bool mySwitch = false;
 
void OnGUI(){
 mySwitch = GUI.Toggle(new Rect(290,20,80,20), mySwitch, "My switch");
 }

Toolbar

A toolbar is a row of several buttons. You can have however many buttons you like on a toolbar, but only one button can be selected at any one time. An integer variable is used to keep track of which button is selected and an array of strings is used for the different buttons.

toolbar

The number of items in the array determines how many buttons there are. For example, if there are three items in the array then there will be three buttons. If the first button is selected, the integer value will be 0. If the second button is selected, the integer value will be 1. If the third button is selected, the integer value will be 2, and so on.

The sample code below shows the integer value variable, the array of strings, and the Toolbar GUI control.

int difficulty = 0;
string[] list = {"Easy", "Medium", "Hard"};
 
void OnGUI(){
 difficulty = GUI.Toolbar(new Rect (0,0,200,30), difficulty, list);
 }

 Textfield

A textfield allows the user to input text. The textfield can display text and also accepts text from the user as they click in the box and type in it. A string variable can be used to store text that is displayed inside the textfield, and then store the text that the user types in.

textfield
The code below shows how a textfield can be added to a scene.

string textInput = "Enter your text here";
void OnGUI(){
 textInput = GUI.TextField(new Rect(600,20,130,30), textInput);
 }

Textarea

A textarea is just like a textfield except that it can store multiple lines of text.

textarea

 

The sample code below shows how to add a textarea control to your scene.

string textInput = "Enter your text here";
void OnGUI(){
 textInput = GUI.TextArea(new Rect(600,20,130,120), textInput);
 }

Sliders

Sliders allow the user to select a value between a range of different values by clicking and dragging a slider with the mouse. You can add horizontal and vertical sliders to your scenes in Unity. The slider takes a float value that is used for the default position of the slider, and returns a float value that contains the value the user changed the slider to. It also takes a minimum and maximum slider value.

sliders

 

The sample code below shows how to add both horizontal and vertical sliders to a scene. In the two examples, there are float variables that are initially set to a value of 0 (inside the main class). Each slider takes a float value and then returns a float value. The x and y positions as well as the width and heigh are specified. Parameters for minimum and maximum values for the sliders are also added at the end of the statement – in this example, the minimum value is 0 and the maximum value is 100.

float horizontalValue = 0;
float verticalValue = 0;
 
void OnGUI(){
 horizontalValue = GUI.HorizontalSlider (new Rect (30, 20, 150, 20), horizontalValue, 0, 100);
 verticalValue = GUI.VerticalSlider (new Rect (5, 5, 20, 150), verticalValue, 0, 100);
 }

In the next tutorial we will look at how to customise and style GUI controls.

User input with forms

We will now start using forms to take user input. Forms include elements such as input text boxes, checkboxes, radio buttons, drop-down lists, and submit buttons.

In this tutorial, we will ask the user to enter their name and then display a personalised welcome message with their name included. In the first example, we will do do just that. In the second example, we will also hide the form once the user has entered and submitted their name.

Watch the video below and then scroll down to see the code.

Here is the code for the first example, where we ask for the user’s name and display a personalised welcome message. Notice that the form still remains after it has been submitted.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Forms</title>
 <script type="text/javascript">
 // This tutorial requires a basic understanding of forms in HTML
 // The form is created in the body section of the HTML page.
 
 function writeName(){
 var welcomeMsg = document.getElementById('welcome');
 var name = document.getElementById('name');
 
 welcomeMsg.innerHTML = "Welcome "+name.value+".<br/>";
 // We append .value to the end of name so that it sets the variable name
 // to be equal to a property which is the value, not the object.
 
 }
 
 </script>
 
</head>
<body>
 
<p id="welcome"></p>
<form>
 What is your name:<input type="text" id="name"/><br/>
 <input type="button" value="Submit" onclick="writeName();"/>
</form>
 
</body>
</html>

In the second example (below), once the user has entered their name and clicked on the ‘Submit’ button, the personalised message will be displayed and the form will also disappear.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Forms</title>
 <script type="text/javascript">
 // This tutorial requires a basic understanding of forms in HTML
 // The form is created in the body section of the HTML page.
 
 function writeName(){
 var welcomeMsg = document.getElementById('welcome');
 var name = document.getElementById('name');
 var formContent = document.getElementById('entername');
 
 welcomeMsg.innerHTML = "Welcome "+name.value+".<br/>";
 // We append .value to the end of name so that it sets the variable name
 // to be equal to a property which is the value, not the object.
 
 formContent.innerHTML = ""; // this removes the form text input box after name has been entered.
 
 }
 
 </script>
 
</head>
<body>
 
<p id="welcome"></p>
<form id="entername">
 What is your name:<input type="text" id="name"/><br/>
 <input type="button" value="Submit" onclick="writeName();"/>
</form>
 
</body>
</html>

Next tutorial: Treating text input from a form as an integer of float