Build an amazing health bar in Unity

Tyler Smallwood
4 min readSep 1, 2023

--

Objective: Create a health bar with UI system.

Making a health bar is really easy. All that is needed is one script and a slider. You will see that I have two text already in the scene, these can be added if you want. First thing to do is add in a slider to the scene.

Next thing we will need to do is disable the handle of the slider for now.

To see the difference between fill and background sections we will change Background to Red and fill to green.

With that done, if you select the slider and change the value, you will notice that the fill bar does not line up to the background 100%. It is set up to be hidden by the Handle and being offset a little would allow the handle to not go beyond the background.

To fix this select the Fill Area and Fill and set to 0.

Next we need to set the max of the slider to 100.

To make them more square, we can select the Background and Fill and set Pixels Per Unit Multiplier higher than one. I settle on 4.05.

Now to have text follow the fill area, we will enable the Handle Slide Area, remove the Handle object and add in a Text component. I will be using Text Mesh Pro.

You will need to set the Anchor Presets to Right Stretch.

Place where you want the number to be, I set mine below the bar. Now on to the script. We will create a new C# Script and use the UnityEngine.UI and TMPro library’s.

We need to get variables for the slider, the Text Mesh Pro text and an int for the amount of health.

Now to add 20 and subtract 20. Use an If statement to check for input for the left and right arrow keys. While also checking to make sure the health amount is less that 100 or greater than 0. Lastly, add 20 or subtract 20 to the correct statement. This will be done in Update.

We will assign the Sliders value to equal the health amount. While also setting the text to the health amount.

Back in Unity all that is left is to assign the objects.

With that we have a working Health Bar.

Thank you for reading, have a wonderful day.

--

--

Tyler Smallwood
Tyler Smallwood

Written by Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

No responses yet