noobtuts

Unity UI Tutorial

Unity UI Tutorial

Foreword

In this Tutorial we will take a closer look at Unity's new UI system. While it's extremely useful, most Tutorials still make it more complicated than it is. We will focus on the fundamentals first and then take a (optional) closer look at the more advanced features like stretching and pivots.

Requirements

Unity Version

Our Tutorial will use Unity 5.1.1f1. Newer versions should work fine as well, older versions may or may not work.

Project Setup

Let's get to it. We will start Unity and select New Project:
Unity New Project

We will name it ui, select any location like C:\, select 3D (although 2D works too) and click Create Project:
Unity Create new 3D Project

The Panel

We will begin by creating a little Panel that holds all of our UI elements later. Please note that UI elements don't have to be on a Panel all the time, we simply create one for the sake of learning.

Let's right click in our Hierarchy and select UI->Panel:
Create UI Panel

It's important that all our UI elements are always children of a Canvas. It's also important that we always have exactly one EventSystem in there, too. Of course, Unity took care of that automatically already:
Canvas and EventSystem in Hierarchy
Note: we don't really have to worry about the Canvas or the EventSystem, it's just important to remember that they are always required.

Alright so let's select our Panel in the Hierarchy:
Panel selected in Hierarchy

Before we continue, let's select 2D mode so that modifying the UI will be easier:
Scene 2D Mode

If we take a look at the Scene then we can see our Panel already:
Panel in Scene
Note: we usually have to zoom out a bit in order to see it in the Scene.

Let's make it a bit smaller by dragging the blue dots around:
Panel resizing
Note: the white rectangle on the outside is supposed to the screen size.

If we press Play then we can see the Panel in game:
Panel ingame

If we wanted to, we could also change the Panel color or modify the image entirely in the Inspector:
Panel Color in Inspector

And that's our Panel, simple as that.

The Input Field

Let's add a input field to our Panel. We will right click the Panel in the Hierarchy and then select UI->Input Field:
Create Input Field

Now our new Input Field is a child of the Panel:
InputField as child of Panel
Note: this means that the Input Field is part of the Panel and it will go wherever the Panel goes. We could also right click just the Canvas and add a new Input Field that has nothing to do with our Panel.

Let's take a look at the Scene and position our Input Field at the top of our panel by simply dragging it around:
Inputfield Positioning
Note: we could also resize it again by using the blue dots.

The Input Field Parts

If we take a closer look at the Hierarchy then we can see how our Input Field actually consists of three parts:
InputField parts

We can modify every part of it by first selecting it in the Hierarchy and then taking a look at the Inspector.

If we press Play then we can now write text into our Input Field:
InputField ingame

The Button

Let's add a button who's only job is to clear the Input Field's text. We will right click our Panel in the Hierarchy and then select UI->Button:
Button in Hierarchy

We will position it slightly below our Input Field:
Button positioned

The Button Parts

Our Button consists of two parts:
Button parts

Let's select the Text in the Hierarchy and then change it to "Clear" in the Inspector:
Button Text in Inspector

The Button's OnClick Event

We want our Button to clear the Input Field when pressing it. Let's select the Button in the Hierarchy and then take a look at the On Click () events in the Inspector:
Button OnClick events empty

We can use the On Click events to call a function in a Script or to modify a component's properties. We just want to clear the Input Field's text property, which means that we don't even need a Script. At first we will click the + to add a new event:
Button OnClick Add

Afterwards we have to specify the Object that should be notified. We will drag our InputField from the Hierarchy into here:
Button OnClick Object

Now we can choose the function (where it says "No Function" right now) and select InputField->string text:
Button OnClick Function

This allows us to set the Input Field's text to whatever we type into this box:
Button OnClick value

We can clear the Input Field by setting its text to the empty string, which is in the box by default already. Of course, we could also use our Button to change the Input Field's text to something like "test":
Button OnClick value test

If we press Play then we can now use the Button to clear the Input Field:
Clear Input Field

Let's also learn how to call a Script's function, just in case we need it some day. With the Button still selected, we will click Add Component -> New Script, name it ButtonTest, select CSharp as the language and then open it. We will create a OnButton function that simply prints a message to the console:

using UnityEngine;
using System.Collections;

public class ButtonTest : MonoBehaviour {

    public void OnButton() {
        Debug.Log("Button was pressed!");
    }
}

Note: the function has to be public in order to be usable by the button event. The function name doesn't have to be OnButton, it can be just about anything.

Afterwards we can click the + again to add one more event. We will drag the Button itself into the Object slot and then select the ButtonTest -> OnButton function:
Button OnClick Script

If we now press Play and click the Button then we can see a new message in the console:
Button OnClick console message

The Text

We can right click our Panel and select UI -> Text in order to add a simple Text element. Let's position it somewhere in the bottom area of our panel:
Text positioned

We will change the Text's text property to the number 100 and center it:
Text Properties

Here is how it looks:
Text centered

The Slider

Let's right click our Panel one more time and select UI -> Slider. We will position it below the Text:
Slider positioned

If we take a closer look at the Hierarchy then we can see that our Slider consists of many parts:
Slider Parts

The most important one is the Slider itself, because this is where we can adjust the min, max and current value as well as the events. The Other parts can be useful if we want to change how the slider looks. For example, we could remove the handle (the circle) to make some kind of health bar.

Let's change the Min and Max Value so that our slider's value is between 0 and 100:
Slider value in Inspector
Note: we also enabled Whole Numbers so that only values like 1, 2, 3 are possible. With Whole Numbers disabled, we would also get values like 1.5 or 2.99.

Displaying the Slider Value

Alright, we want to display the Slider's current value in our previously created Text element. Let's select our Text element in the Hierarchy and then click Add Component->New Script. We will name it TextChange, select CSharp as the language and then open it.

Our Slider's OnChange event requires a function with one float parameter, so let's add one:

using UnityEngine;
using System.Collections;

public class TextChange : MonoBehaviour {

    public void Change(float f) {

    }
}

We can then use GetComponent to access the Text's text property:

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

public class TextChange : MonoBehaviour {

    public void Change(float f) {
        GetComponent<Text>().text = f.ToString();
    }
}

Note: it's important that we add using UnityEngine.UI to the top, otherwise Text won't be known by Unity.

Alright, now we can select our Slider, add an event by clicking the + button and then drag the Text into the Object slot:
Slider OnValueChanged object

Now it's time to select the function that should be called. If we click on the list (where it says No Function) and select TextChange then we can see that our Change function is in the list twice:
Slider OnValueChanged functions

The first function is detected as Dynamic, which means that the Slider will automatically call it with the current Slider value as parameter. The second function is detected as Static Parameter, which means that it will still be called whenever the Slider's value changed, but it will be called with a fixed Parameter that we can set on our own - just like the text string that we used in our Button event.

Long story short, we will select the Dynamic Change function (the one on the top). If we now press Play then we can see how changing the Slider also changes the Text:
Slider ingame

Anchor Presets aka Stretch & Pivot

Let's get to some more advanced features. Right now our Panel is in stretch mode, which means that its size is always relative to our screen size. So if the screen gets smaller, the panel will also get smaller. This is sometimes useful (especially when a game should run on many different platforms) and sometimes not so useful.

We can see the stretch effect if we change the Scene size in Unity:
Panel stretching

Let's select our Panel in the Hierarchy and then take a look at the Inspector, where we can see that our Panel's Rect Transform has this weird rectangle with two blue arrows and stretch written outside of it:
Panel in Inspector with Stretch

If we click on the rectangle then we can see all the different Anchor Presets that are available:
Stretch and Pivot options

The following image helps us to choose the correct one. First of all, the red options are for a fixed size and the blue ones are for stretching:
Stretch and Pivot Options help

In our case, we want the Panel size to be fixed, which leaves us with one of the red options. Now we just have choose the pivot, which is simply the relative position. We want our panel to be always in the center of the screen, so let's also select the option in the center:
Stretch and Pivot options fixed center

Quick summary:

Note: even though we selected the centered pivot, it does not mean that our Panel has to be exactly in the center. We can also position it 10 px below the center and the pivot makes sure that it's still 10 px below the center even if we change the Screen size.

Now our Panel always stays the same size, even if we resize the Scene:
Panel stretching fixed

Tweaking the Canvas

Let's take a closer look at the Canvas. If we select it in the Hierarchy then we can see a few interesting properties in the Inspector:
Canvas in Inspector

The first interesting option is the Pixel Perfect property. We can enable it to make the UI look sharper:
Canvas Pixel Perfect

Another very interesting property is the Render Mode. Let's set it to World Space, change the Canvas Pos to (0, 0, 500), the Rotation X to 45 and the Rotation Y to 45 to see a 3D UI:
UI in worldspace

The World Space mode can be used very creatively, for example for a hologram text or a speed indicator inside a space ship's cockpit. The possibilities are endless!


Download Source Code & Project Files

The Unity UI Tutorial source code & project files can be downloaded by Premium members.

All Tutorials. All Source Codes & Project Files. One time Payment.
Get Premium today!