Working on a project recently, I came across a very simple, and obvious way of creating a color changing HP bar (or any progress bars) in Unity, that change color based on the amount of health left. And yet I have never seen this being used, and never used this myself before. In the next few minutes, you’re going to learn the fastest way, of making color changing HP bars.
UI setup
So first let me show you the scene setup I have in place. There’s a simple HP bar, and a couple of buttons to increase or decrease the health.

The HP bar is a simple Image for bar background, and another UI image with Image type “filled” which is the actual bar part. There is a TextMeshPro text gameObject in the ‘OtherUi’, along with the + and – buttons to increase and decrease HP which will be indicated graphically by the filled bar and the TMP text.


Code
Alright!, now that you’ve seen the scene setup, let’s get to the code part.
So I created a new Script called ColorHP.cs , and here’s the code :
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ColorHP : MonoBehaviour
{
public TMP_Text currentHpText;
public Image filledBar;
public Gradient hpGradient;
private int currentHP;
public int maxHP = 100;
void Start()
{
currentHP = maxHP;
UpdateUI();
}
public void PlusHP(int changeAmount)
{
currentHP = Mathf.Clamp(currentHP + changeAmount, 0, maxHP);
UpdateUI();
}
public void MinusHP(int changeAmount)
{
currentHP = Mathf.Clamp(currentHP - changeAmount, 0, maxHP);
UpdateUI();
}
void UpdateUI()
{
currentHpText.text = currentHP.ToString();
filledBar.fillAmount = (float)currentHP / maxHP;
filledBar.color = hpGradient.Evaluate(filledBar.fillAmount);
}
}
Inspector setup
Then I added the script to the parent “HP bar” gameObject. Assigned the required fields for variables “Filled Bar” and “Current Hp Text”.

Then I made the color changes in Hp Gradient, you can do so by clicking on the gradient. you can click on the lower edge to create a Color Key, and upper edge to create a new alpha key. Mine looks like this :


Then I assigned the “PlusHP” and “MinusHP” functions to the + and – buttons, and put a change value of 10.

And that’s it, we’re ready to test the Color change functionality.
Color Changing HP Bar in Unity – The Final Result
Using the gradient gives you much more flexibility over the color control then any other way like Lerping between colors would.
If you want me to explain how the code works, or how to make a progress bar UI, let me know in the comments.
I hope you found this useful, and that you’ll use this for your games.
I’ll be uploading a tutorial for this on YouTube soon, covering how the code works as well, for that follow me on twitter (@BuluSama) to stay updated.
Have a nice and productive day!!!
Get notified of new articles and have fresh tech news delivered straight to your inbox.

You must be logged in to post a comment Login