Unity UI — Building a Health Bar

Sean Duggan
3 min readJun 27, 2024

--

A reasonably common use case for Sliders in Unity is health bars. It’s a pretty natural fit, with defined beginning and end values, and a strict continuum. Let’s make one. We’ll start with the usual background, and then put a slider on there, making it operate between 0 and 100 (defaulting to 100), and with the Background red and the Fill green.

Now one thing you may notice in the above images is that, at health 0, and health 100, there’s still a bit of other end of the bar. That’s easy enough to fix, by zeroing out the Left and Right values for the Fill and Background. Now, to provide our hurting and healing, I added two buttons, as well as a class with methods that can be called when hurting or healing.

public class HealthBar : MonoBehaviour
{
[Range(0, 100)]
[SerializeField] int _health = 100;

[SerializeField] Slider _healthBar;

[SerializeField] int _healAmount = 20;
[SerializeField] int _hurtAmount = 20;

private void Awake()
{
Assert.IsNotNull(_healthBar, "Health bar not set!");
}

private void Start()
{
_healthBar.value = _health;
}

public void Heal()
{
_health += _healAmount;
_healthBar.value = _health;
Debug.Log($"Healing {_healAmount} with result of {_healthBar.value}");
}

public void Hurt()
{
_health -= _hurtAmount;
_healthBar.value = _health;
Debug.Log($"Hurting {_hurtAmount} with result of {_healthBar.value}");
}

private void Update()
{
if (Input.GetKeyDown(KeyCode.Minus))
{
Hurt();
}

if (Input.GetKeyDown(KeyCode.Plus))
{
Heal();
}
}
}

I’ve also provided a way to do it via keyboard input. And, how does it work?

Huh… nothing. The keyboard commands work fine, but not the buttons. As it turns out, the reason is simple. My scene is missing an Event System. I don’t know if I accidentally deleted it, or there was an issue from me re-using that background, but none was added to the scene, so button input isn’t being picked up. Fortunately, that’s easy enough to fix.

And, now it works. Excellent!

--

--