Building a Health Bar in Unity
Health bars are a common UI element in games and while simple in understanding, they can be difficult or complex to implement. Today, I’m going to discuss turning Unity’s UI Slider control into a health bar.
The slider control has three parts. The first is the Background. This is area is the default look of the slider before the slider is moved. In the above image, it’s the area to the right of the slider handle. Next, the Fill Area controls what the slider looks like as it fills up. In the image above, this is the area to the left of the slider handle. Finally, the Handle Slide Area controls what the handle looks like.
To create a health bar, starting with a slider is a great idea as most of the work is done for you. Once the slider is in place, there’s a few steps left to get the job done.
Step 1. Change the color of the Background. I’ll use a red color to indicate lower health. I’ll also set the Pixels Per Unit Multiplier to 5 to make the round corner at the end more like a box.
Step 2. Change the color of the Fill Area. I’ll use a green color to indicate higher health. Just like the background I set the Pixels Per Unit Multiplier here to 5 as well.
Step 3. Since user interaction isn’t needed for the health bar, the handle in the Handle Slide Area can simply be turned off.
Step 4. Set the Min Value and Max Value for the health bar. In this case, I set them from 0 to 100.
Step 5. Control the health bar from code. The Slider and a text field are exposed to the Unity UI via SerilizedField attributes.
To update the health bar, all that’s required is setting the sliders value property.
When the game is run and health values are changed, the UI shows the current health value.