2D modular health system in Unity part 1
Objective: Make it so that the health script can be dropped on any object that needs a health bar
With this two part series I want to show how to create a modular health component that comes with a health drain and heal ability.
This is a pretty simple thing to do once you know how, so let’s get started.
First, create a C# script and call it something related to Health. My script is called Health.
In this article I will focus on just removing health and adding health back to the gameobject with the script attached.
in your new health script create 3 fields with similar names to:
In the start method, I set my currentHealth to the maxHealth. I have made the fields serialised so that I or another developer can change them in the editor without having to amend the code base.
Once you have these set up there is another field to add which is an image.
Save the script and go into the editor. Adjust the fields in the editor and drop in the Image you want to use for the health bar. If you haven’t already got one set up, then please go ahead and create a UI -> image and then select a standard sprite. Do not set the currentHealth field as this is set in the script, this is just so you can see it change in the editor when playing.
Go back into the script and create a new void method called HealthBarFiller and make sure to add this method to Update().
One more thing to go over before we start coding, on the sprite renderer on the healthbar image, make sure to change the image type to filled. This will allow us to change the sprite in code. I have chosen Radial 360 for the fill method as I have a circle health bar, so choose the option relevant to you.
Now, in the new method write the following:
This makes it so that the image fill amount will change depending on the result of the currentHealth divided by the maxhealth.
To test whether this is working we still need to create two methods, one for damaging and for healing.
With both of these methods I am passing in the amount to heal and damage the gameobject. This means that different enemies or weapons can damage different amounts.
Now, to call these methods to test you can create some inputs in the Update() method and test them in game.
And thats it for part one, come back for part 2 where I add the healthbar to the player and show you how to move the healthbar down gradually instead of instantly, which looks way better.