Building UI elements made easy with Unity

Matthew Bartosh
3 min readJul 29, 2022

My objective for the day is to create a score tracker, to better gamify the experience and let the player know how they’re doing.

First I’m going to create some Text in the Hierarchy by right clicking and checking under UI. This will also place an EventSystem, as well as a Canvas who will act as parent to the text I just created.

The Canvas is a large box in the scene view that will allow me to place and organize my UI within it. The EventSystem will let my users interact with the UI I’ll create.

The Canvas with text placed and locked to the top right corner so it scales properly with the screen size, colored white.

Next, I’m going to tell the Canvas to scale with the screen size as well, so if someone players with a smaller or larger screen than me (or if I want to push the game to mobile) everything scales properly.

Now I’m going to actually implement code to track the score with enemies being worth 10 points each, first I’m going to include using UnityEngine.UI; at the top of UIManager.cs to be able to use the Text variable and I’m going to attach my UIManager to my Canvas.

I’m going to store _score on my Player, and create a way to call it from Enemy when they’re destroyed by a laser.

The bottom section from Enemy.cs calls on the Player.cs to add 10 points to _score, which is then subsequently passed to UIManager.cs.

You’ll notice I’m checking _uiManager here, which is defined by _uiManager = GameObject.Find(“Canvas”).GetComponent<UIManager>();. Also, coding it this way will allow me to change the points enemies are worth, make the point values a range, or even add more enemy types that could potentially cost different point values.

All that’s left is updating the game text in UIManager.cs.

Time to test it out!

Looking good so far! Now that I have a score counter, I’m going to be adding a life counter and a retro game over screen. Join me next time!

--

--