Scoring - Part 2 (Add a UI to display the score)

2D Game Design with Unity

🕑 This lesson will take about 14 minutes

In this lesson, you will learn how to implement a user interface to display the score to the user. In the previous lesson, we implemented a scoring system using two scripts (‘PlayerController.cs’ and ‘Scoring.cs’). We wrote code that would detect player collisions with collectables (eg. gems, coins) and increase the score. We also used a single variable for the score so that the score could be maintained across different scenes/levels.

Now that we have a scoring system, we need some way of displaying the score to the player. We need a user interface (UI). This is achieved by adding a canvas to the scene. A canvas is used to place different UI elements on-screen such as text, buttons, menus, images, etc. We will create a Text object which will be placed on the canvas (as shown in the image below). The text will be updated throughout the game to reflect the player’s current score. This will be achieved by adding some code to the existing script called ‘PlayerController.cs’ (no changes or additions are made to the ‘Scoring.cs’ script in this lesson).

Screenshot of a 2D platformer game showing a user interface with text displaying "Score: 2" to the user.

Game art, tiles and sprites from the Free Pixel Space Platform pack are used in this lesson video and can be downloaded from the Unity Asset Store.

Watch the video below and then scroll down for the sample code.

Is YouTube blocked at school? Watch on Google Drive.

Sample code for PlayerController.cs script

Next lesson: Implement a Health Bar