Build a Health Bar in Unity 2021 URP
In this article we’ll go over how to use Unity’s UI Slider to create a health bar.
Although we will be doing it on a menu, this could also be used on a canvas that is attached to the player game object in world space.
Initial Scene Setup
To get this jump started, I’ve already placed a Canvas and several child elements in the scene.
If you’re jumping into the deep end and find yourself lost, please see my previous articles on Unity’s UI system.
There are a couple UI Image elements, for both the menu background and the title background.
There are also two Text Mesh Pro (TMP) Text elements for the label “Health” and the current health amount in numeric terms.
Adding the UI Slider is as simple as any other UI element and is shown above.
We want to also make sure that this slider is a child game object of the overall menu or dialog box so that it will move with everything else in proportion and scale correctly.
If we go through the various elements of the Slider element, we can disable the handle (who wants players to control their own health?!).
Let’s also give our Fill element a color to differentiate it from the background color of the slider.
On the Fill Area element, set the Left and Right fields to 0.
On the Fill element set the Width to 0.
Now, let’s create a script to control our UI and assign it to the Canvas element.
Attaching the Player Health Amount to the Slider
Let’s child our text element for health amount to the slider itself.
Disable the “Knob” image on the Handle element.
When we manipulate the HealthSlider element’s value, we can see that the slider is dragging our text field along with it as desired.
It looks a bit off at 100%, but if our player hast hat health it won’t be one digit, but rather 3 and that looks pretty good.
We can add another UI Image and set the color to a dark grey.
After resizing and repositioning, it will serve as a nice border around the health bar.
Now set the Color of the Background element to red.
That is looking pretty good!
One last thing before we get into the code, let’s set the Max Value field of the HealthSlider element to 100 so that we don’t need to normalize our health value.
Code Monkey Time
Our script is pretty straight-forward, we just need to remember our using statements for the UI, TMPro, and the Input System.
After that, we need to store some of our UI elements and an integer variable to represent current player health.
A quick and dirty add/subtract health depending on keypress and we are good to go.
Before we can run our game however, we need to assign the slider and the text field to our UIManager_HealthBar script component.
Now we can run the game and see that our health slider is working exactly as intended!