Ease of Building UI Elements in Unity

Working Score UI in the top right corner

One of Unity's best features is how easy it is to create amazing UI(User Interface) systems for both video games and enterprise applications. UI allows for easy implementation of showing score, player lives, main menus, and game over screens.

Objective: Create a scoring system that displays points on the screen for every destroyed enemy.

The first thing we need to do is add in a text UI in the Unity editor’s hierarchy:

This will create three things:

  1. Canvas -this is what makes up the entire UI. Every UI element added will be added to the canvas.

Make sure to name the text what you want, in this case, Score_text.

And in the text component, type in what you want the text to say, adjust the font and color of the text to your liking.

Adjust the text to whatever you want

Now that we have the text, we need to anchor it to the screen's top right. If the game is scaled differently, the text would be outside the screen's bounds.

Using the Rect Transform component, adjust the anchor preset to the top right corner and adjust the X and Y pos values to fit.

Lastly, on the Canvas Scaler switch from “Constant Pixel Size” to “Scale With Screen Size.”

Scale With Screen Size

Scale with screen size will always keep the size of the text proportionate to the screen's size.

text will always scale with screen

Now creating the behavior for the Score System. Create an empty game object and script called UI_Manager and open it up.

Now we create a variable for the score in the player script:

We now need to access the “UnityEngine.UI” directive. And add in a Text variable called _scoreText.

Using UnityEnigine.UI and create a Text type variable

This will allow us to now store and call text in a variable, and we can drag in the Score_text into the UI manager.

Now we create a player script method that allows the score to be called elsewhere to add to the score. If the player's laser destroys the enemy, The points from the enemy will be added to the score total in the player script:

Adds points to score
where and how many points are added

The last thing to do is update the score total to the UI in Unity. To do this, we can create a method in the UI Manager Script to have the Text always read “Score: However many points” and call it from the AddScore method in the Player script.

public void UpdateScore

Learning to become a unity game developer