Ease of Building UI Elements in Unity

addam davis
4 min readMay 23, 2021

--

Objective: Create elements for your UI.

UI stands for User Interface.

It uses sprites, text, images, and many other forms to display information to the player.

We are going to make a text-based element to display our score in the upper right hand corner of the screen.

To begin there are two methods to curating an UI manager. Some people make an empty object to represent their UI manager. Others, use the Canvas that is automatically created when you create your first UI element.

Right click in the hierarchy and scroll down to UI then Select Text.

This will create the text element as well as a Canvas and Event System.

Every UI element will go under the Canvas.

Event system will allow you to hover over buttons and levers and allow you to interact with the UI.

Rename the Text element to “Score_text”

Edit the color of text to be easily seen. If the background is dark, us white.

Set the font size to be easily readable.

Position the text where you want it and use the Anchor function to lock the element there.

Under the Canvas inspector view there is a component named canvas scaler. change the UI scale mode to scale with screen size.

Now everything will stay relative to its position no matter the screen size

Now create a script and name it UIManager. Attach the script you desired Manager(Canvas, or an empty object named UI Manager.)

On the player script we need a variable to represent the score.

On the UI manager script, we need to create a handle for the Text, however, to do this we need to add a using function to the top of the script.

using UnityEngine.UI;

With this function added we now have access to the Text component.

Drag the Score_text and place it in the score text reference on the inspector view.

Under the Enemy script create a global reference to the player and cache it.

This allows us to use Get Component only once

To receive points from the Enemy

Set the type of information this method receives.
The number in the Parenthesis represent the amount of points and can be set to random

To communicate with the UI Manager, create a handle and cache it on the player.

Using this method to cuts down on the expensive Get Component command

Always remember to null check

This help ease bug catching later

On the UI Manager script

Setting the local variable to an int so it only works with whole numbers.

Finish it off with setting the player score on the player script with

The points from the enemy are converted on the player and sent to the UI Manager.

Now with every kill we can see our score increase on our UI. You could use this function for Ammo count, Time keeping, and many more functions. Experiment with UI and I’ll see you, in the next Tutorial!

--

--