Displaying Player Lives — Unity UI
In the last article we finished up updating our Score in real-time every time you destroy an Enemy. In this article we’ll be displaying our Player’s remaining lives, decreasing by 1 each time we’re struck by an Enemy, making it easier to tell how much health we have left!
Creating our Lives Image
Instead of using a Text UI element like we did for the Score, we’ll be using Images to display our Player’s Lives.
So first we’ll create an empty UI Image on the Canvas in the Hierarchy:
Luckily, with our assets we were given some Sprites to use for or Lives UI display. We’ll attach one of those Sprite Images as the Source Image, anchor it to our top-left position on the screen, and position it accordingly.
If you run into the issue of your Image looking squished like in the example below, you may just have to click “Preserve Aspect”. This keeps the Images aspect ratio intact!
This first Sprite is just a placeholder to see how the display will fit. Next we’ll be utilizing the display through code.
In the UIManager script
Now that we have the basis set up, we can get more intricate. Inside of our UIManager script, we’ll create a Sprite[] Array, and a reference to our Image UI that we just created.
Then in the Inspector, with our Canvas selected, we can link these new fields.
For the Lives Sprites Array, we’ll utilize our Sprites that display 0–3 lives.
And we can’t forget to link the Lives_Dispaly UI Image, since that is what we’ll be updating with our Sprites Array!
Next we’ll go back into out UIManager script and create a function to update our lives display:
This requires an int to be passed in, that will coincide with the index of the Sprites Array. For this reason, I recommend linking your Lives Sprites array in the Inspector as such. (Element 0 = 0 lives, Element 1 = 1 life, etc.)
This function then updates the current “Source Image” of our Lives_Display UI Image to be one from the Sprite Array.
Calling UpdateLives() in the Player script
The next thing we have to do is make sure our new function is being called in the appropriate place. Since our Player is handling the logic when our Player gets damaged, that will be the best place.
So as soon as our _lives decreases (when we are damaged), then we’ll update our Lives Display:
And just like that, we can now easily see how many lives of Player has left, and how cautious we need to be facing future enemies!
In the next article we’ll be making a Game Over screen!