2D modular health system in Unity part 2

Daniel Kirwan
3 min readOct 14, 2021

--

Objective: make it so that the health bar is attached to the player and moves around with them

With the second part of this series I want to show how to get the healthBar to always be around the player.

To do this you need to create a UI -> image on the player gameObject. Left-click the player and the right-click and create the UI -> image. Rename the image object to HealthBar and then click back on the canvas object and drag the health script to the canvas.

Once you have done that you will be able to drag in the new health image to the field available on the health script component.

In the Health script I have created two new fields. One for the LerpSpeed, which will be the speed that the healthbar image updates and an offset for the image.

In the Update method set the lerpSpeed to be:

In the previously made method called HealthBarFiller() from part 1 of the series you will need to change the code to the following.

The above method now moves the image gradually up or down depending on the currentFillamount, the new fillAmount and the speed to change it over.

To get the same colour change that I have, create a new method called ColourChange and make sure to start calling this in Update after the healthbarfill method.

This does a similar process to the method before, just with colour. I have selected that I want to move between green for 100% and red for 0% and then set the colour of the image to that new colour.

The main reason that I have created a canvas on the player for the healthBar is so that we know where it is without having to make an expensive function call in getComponent or find a game object by tag.

I created a method called MoveImage() and this basically just moves the image around the screen where the parent object is. And the parent object is the player.

If you have created the offset as serialised like I have, then you will be able to adjust the image position in the editor. I have a circle image so, I do not have to move the image, but if you want a horizontal bar above the player or enemy, then add to the y-axis and adjust from there.

But how do I call this from another class you say? Well I have lasers firing, so when the enemy detects a playerLaser, it will take the damage amount from the laser and then remove from the health.

And that is it, all I did to get the health on the enemy was to create a prefab of the canvas from the player object and then drag it onto the enemy. I then has a working health system on both the enemy and player.

--

--

Daniel Kirwan
Daniel Kirwan

No responses yet