Hey everybody! How was everyone’s first week of summer? Any new or exciting plans out there for anyone? Myself…? Not much given that the pandemic is still very much present where I live – although places are starting to open up these past two weeks. Needless to say, I will continue each week towards my goal in completing the 3D Platformer course by this Fall. Without further ado, I will demonstrate how to update the UI to display the player’s health today.
Back at the start of Week #6, you may recall a UI object called a canvas being added to the game scene. The canvas is used to display UI elements such as the UI image for a fade in/fade out black screen added earlier. A new UI element introduced today is the UI text which is created and added to the canvas to display the player’s health points:
In addition to displaying the player’s health as text, a UI image is created and added to display the player’s health bar. To keep the UI elements organized, an empty called ‘UI’ is created containing the text and image:
And as always, in the ‘UIManager’ script, variables are declared to be assigned by the UI HealthText and HealthImage:
Next, similar to how an array was created in the ‘PlayerController’ script to store all the player pieces (or game objects found in the player armature), an array is created in the ‘HealthManager’ script to store all the images (or sprites) for the player health bar:
Finally, in order to update the player health points and health bar, a function called ‘UpdateUI()’ is added to the HealthManager script (see below). Appropriately, the ‘UpdateUI()’ is called in four functions within this script: “Hurt”, “ResetHealth”, “AddHealth”, “PlayerKilled” – essentially any function which would cause the player’s health to change.
As you can see in the script above, instead of using ‘for loops’ (as I have done all along), I learned to use “switch statements” this time – another way to write conditional statements.
And alas, to see the player health UI (text and image) update in the game as the player takes damage, heals, is instantly killed, and respawns:
And with that, that concludes this week’s blog post! I was hoping that I would have enough time this past week to move onto the next course lesson and add the next object to the scene, but work has been rather busy as usual. >< So, that will have to come about next week!
Have a good week everyone and stay safe!