But how do you add a health system to your own games?
What You Will Learn
On the surface, this project may not seem complicated.
Despite this, youll need to understand several key Unity3D coding concepts to create a working health bar.
To get started, you could follow ourphysics-based Unity3D character controller guideto create a player model with basic controls.
With a scene and player model in place, its time to add a UI element.
Right-click inside the Hierarchy window and selectUI>Image.
This will create two new items in your hierarchy: a Canvas parent object and an Image child object.
Change the name of the child object to Healthbar.
Choose a width, height, and position for your health bar using the inspector.
Just double-check that it is above the health bar in the hierarchy so that it displays behind it.
Go to the Project pane, right-click, and selectCreate>2D>Sprites>Square.
you’re able to also changeImage Typeto Filled,Fill Methodto Horizontal, andFill Originto Left.
Now if you run your game and use theFill Amountslider you should see your health bar shrink and grow.
For example, a playerHealth of 0.5f is 50% of the health bars width.
Start by creating a new script file called Health to house the code.
The following code goes into the void Update() function.
This process starts with finding the game object that owns the variable.
And, finally, you’re free to extract the specific variable youre looking for.
In this case, its the playerHealth variable you added to your character controller.
Assign this to a float variable within the current script called currentHealth.
This is a little boring, though, and it could definitely do with some color.
Next, add an if statement to check whether the players health is above 0.3f, i.e.
30% or more.
If it is higher than 0.3f, set the health bar to match the color you just added.
If it is below 0.3f, turn the health bar red.
Of course, though, you need a way to test your code.
you might add a single line of code to the Character_Control script to make testing possible.
Whenever the player presses the W key to move forwards, remove a small amount of health.
Of course, though, it never hurts to read more guides.