Day 21 of my Developer Journey: UI and Score

Marek Ondrej Valco
3 min readDec 18, 2021

--

Objective: Create a tracker for the player score

First we will create UI text. This will add a canvas and a Event system to our Hierarchy.

Now in our hierarchy after creating UI text

Next we will anchor the text to the top right corner and change the canvas settings so that the size scales with the screen size.

This will lock our text to the right corner
Canvas default settings
Canvas scaling settings

Now for the tricky part, code communication. We need a new script for the UI manager. In this script, we will keep track of our score. We also need to add “using UnityEngine.UI” to the top of the script. In the script we will assign our text to the script with the _scoreText variable.

New Script for the UI manager

Within our player script we will need to create an int value to track our score.

Variable that keeps track of our score

Also, we will need a method that add score to our value.

Add Score method on the player

This may look complicated, but is simple to read. Our method will add an int value of points, which we will assign in our enemy script, to our score and communicate that change to the UI manager.

Within the enemy script, we will add a few changes. First, we will look for the player in void start, so we can communicate with the AddScore method. We do this in void start to cache that variable and not have it being done over and over again with each enemy for performance enhancement.

Looking for the player and the player component

Next, as we destroy an enemy, we will add points to the players score.

Uppon colliding with the laser, the enemy gives the player points

Now, in the UI manager, we can update our score, according to what the _score variable on our player is!

Updating our score text

Objective: COMPLETED

--

--

No responses yet