UI score system in Unity

The next key element in any game is a UI. We will talk a little about a Unity UI and we will create a scoring system.

First, we need to create a UI Text. Right-click on the Hierarchy panel, go to UI, and choose Text. Apart from Text, this will create a Canvas and Event System. Chamge name of your Text to “Score_text”.

Canvas is a place where all UI elements should be created.

Event System is what lets us interact with UI elements like buttons or sliders.

Change the color of our text to white and set the font size to 20:

Not we need to position our text in the corner of our game. We will use anchors to do so:

The next step is to make our text scale to screen size:

We have our score text, now we need to create a script that, every time we kill an enemy will add a score.

Create script “IUManager” and drag it to your Canvas.

Go to Player script and add a private variable _score:

Create a public method called AddScore(). Then we will take our current score and add 10 points.

Now we need to called this method from enemy script when it collide with the laser.

We find Player script in the Start() method, and after enemy is hit with a laser, we call AddScore() method.

Create a variable called _uiManager:

Now we need to use GetComponent(), and check if our _uiManager is empty.

Go to UIManager script and add Text variable called _scoreText and assign it in the Inspector.

ADD “using UnityEngine.UI;”

In the Start() method change text to “Score: ” + 0

Create method called UpdateScore() and pass in “playerScore” value.

Now, we need to update our score. Go to Player script and in the AddScore() method call UpadeScore() method:

And we have a working scoring system!