UI in Unity: Creating a Health Bar

Zac Bogner
4 min readJan 26, 2024

In our recent article, we created a Mini-Map.

This article will focus on Creating a Health Bar for the Player Character.

We select our Sprite Image for the Health Bar and Create a Slider GameObject.

For the Health Bar on our Player Character, we will focus on the Slider values to control our Health.

Next, we will make our Player Health Script.

We will need access to our health Bar Slider, and health Text, and create a health amount with an integer, initializing health on Start (i.e. Starting with Max Health of 100).

We create our function OnCollisionEnter in the instance we want to collide with the Enemy and take Health away from our Health Bar.

Then we get a reference to the Slider component and set our health.

Next, we decrement our health by a value from 100 (being our maximum health).

We then get a reference to our Text component.

For this example, we attach a Rigidbody physics component and freeze the rotation and y position, since we don’t have movement currently.

To further test, and improve the conditions above we will make a safety check that detects if our heath is > 1 and < 99 (100).

So, if(health ≥ 1) we then begin to decrease our health. To do this we split our health checks with Input A (-health) and D (health+) called in Update.

If our (health is ≤ 99) we increment our health.

We then go back to the slider and set the health to 100 for the max value.

Now our health increases and decreases when we press the A or D key.

Additionally, we can add a background for our slider image.

Next, we notice the health bar doesn’t go all the way to our min or max value when reached, we can make an additional check for our min and max values reached on the slider, then hard set the health value to 0 or 100.

Now our health bar uses all the slider value regions from 0 (min value) to 100 (max value).

We have made our health bar, next will be a custom loading screen article.

--

--

Zac Bogner

Game Designer and Level Designer, formerly with Rainbow Studios. Focused in Unreal Engine with experience in Unity. Former Race Car Driver.