Project 1: Space Shooter

Ease of building UI elements in Unity

Adding score and lives to the game

Score and lives update as planned!

The next step to make my prototype feel more like a game is to add some UI elements. As my game is a shooter style game, it needs the score and lives or health of the player. Let’s start with the simpler one, that is the score.

To add a score to my game, I first have to add a UI element called Text TextMeshPro for it. This can be done from the right click menu of the Hierarchy view. After I do that, it makes a new GameObject called Canvas in the Hierarchy view, and that has the Text (TMP) GameObject as a child.

Adding a UI text element in Unity.

Before I move on, I should also make the Canvas to scale with the screen size. That way a decent sized text in the large screen won’t fill the entire small screen. This can be achieved in the Canvas’s Inspector view by selecting the option Scale With Screen Size in the Canvas Scaler component and its element UI Scale Mode

Now that I have my score on the screen, it’s time to add the lives as well. For this I add a new UI element called image, this will also appear as a child object in the Canvas. After placing it on the top left of the screen, I’m done with the UI elements for now.

Adding the lives image.

Next is the logic for these two. Most of it is the same as before, adding methods and calling them from other scripts, but there are few points that are different with the UI.

First, I have to use two new namespaces in my UIManager script, which is attached to the Canvas, if I want to manipulate the UI elements. To use those namespaces, all I have to do is to add the lines using UnityEngine.UI; and using TMPro; after the other namespaces that are already there. Then I can update the score just by assigning the new score value to my Text element.

The new namespaces that I have to use.

Then the sprites that I use for displaying the player’s lives, these I will save in a Sprite array. To make life easier for me, in the first cell of the array I save the sprite for zero lives, and in the last the sprite for the full health.

Why is this easier for me? That’s because my player has only three lives, so I can use that type number to index my _livesSprites array. Which means, when my player is at full health the _lives number is which is also the index for the full health sprite. At index I have the sprite where the player has two lives left and so on.

Updating the player’s score and the lives left.

Finally the sprites are displayed on screen exactly the same way as the Score_text, that is I assign the correct sprite to the Image element.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store