Unity UI: Updating score for a 2D game

Austin Young
3 min readAug 3, 2023

--

Using Unity’s built in UI tools and with a little c# scripting I was able to create an updating score counter for my 2D vertical shooter game. The Unity UI tools are easy to use but understanding how you want your scripts to communicate with each other to run the functions can be a little tricky. For instance, there are multiple ways to achieve these same results but some methods are better than others.

When I first setup the score UI, I made my existing private score variable into a public variable so that my UIManager could use it. And it worked, however, I learned that a better approach is to keep the score private and communicate to the UIManger through the player script instead and just call a UIManager script method using score as the parameter.

First off though you will want to right-click in your hierarchy to create a new text or textmeshpro. Newer versions will default you to TMP so it’s best to learn it.

You will want to rename your text element, and using the scene canvas, reposition your text object into the desired position. It also helps to use the anchor system in the top left to anchor it to a corner. Reminder: under your canvas you will usually want to change the UI Scale Mode element under the Canvas Slider component to — Scale with screen size.

Now you will want to create a UIManager script to attach to your canvas or UI_Manager object that will update your score in game.

Remember, you will need to add using TMPro; using UnityEngine.UI namespaces at the top of your script to use TMP_Text.

Next I created the following method inside the UIManager script:

UIManager’s UpdateScore method

This method will update the score text to say “Score: “ and then whatever integer variable is passed through it’s parameter. In void start I set _scoreText.text = “Score: 0” as well to ensure that the score is reset at the start of every load.

Next I needed for my player script to use that UpdateScore method so it can pass our existing score method where the score is updated by the passing of an integer variable named points that our enemy script gives us upon destroying.

To do this I will call the following lines to find the UIManager script and gain access using the player script.

Which allows us to call _uiManager.UpdateScore(_score);

the player script using UIManager’s UpdateScore method setting score as the parameter

Et voila, the score text on the game UI should now update the score of your game as you play in real time.

Score in top right updates by +10 as we destroy an enemy

--

--

Austin Young

o/ I'm a game dev documenting my journey. Mostly technical tutorials. Currently focusing on the Unity engine. My Portfolio: ajamesgames.wixsite.com/website-83