Menu
CoddyTech

Health Bars

Part of the Building Real Games section of Coddy's Unity journey. Lesson 10 of 56.

A bar that empties is a UI Image with its Image Type set to Filled. That setting appears once the Image has a Source Image; with None, the Inspector hides it. Fill Method Horizontal with Fill Origin Left shrinks the bar toward its left end, and fillAmount, from 0 to 1, is how much of it is drawn. A dark Image behind it shows the empty part. Unity clamps fillAmount, so 1.4 draws a full bar and -0.2 an empty one.

fillAmount is the part of the health left: the health divided by its maximum. With int fields that is an integer division, and 350 / 500 is 0, so cast one side to float first. Image lives in UnityEngine.UI. This boss bar is updated after every hit:

public Image bossBar;
public int bossMaxHp = 500;
private int bossHp = 500;

public void Hit(int damage)
{
    bossHp = Mathf.Max(bossHp - damage, 0);
    bossBar.fillAmount = (float)bossHp / bossMaxHp;   // 350 / 500 = 0.7
}

The bar's color can follow the health too: bossBar.color = Color.Lerp(Color.red, Color.green, bossBar.fillAmount); is green when the bar is full and turns red as it empties.

challenge icon

Challenge

Easy

The knight has a shield that soaks up damage before her health does. The arrows walk her (Mover.cs), and the spikes hit her for 30 when she steps on them (Spikes.cs). Write Knight.cs; the scene links healthBar and shieldBar, which are empty in the scene:

  • hp starts at maxHp (80) and shield at maxShield (40), and both bars start full.
  • TakeDamage(int amount): the shield takes as much of the damage as it has left, and the rest comes off hp, which never goes below 0.
  • After each hit, both bars show what is left: shieldBar the shield out of maxShield, healthBar the hp out of maxHp.

Press Play, walk onto the spikes a few times, then Check.

Try it yourself

using UnityEngine;
using UnityEngine.UI;

public class Knight : MonoBehaviour
{
    public Image healthBar;
    public Image shieldBar;
    public int maxHp = 80;
    public int maxShield = 40;
    private int hp;
    private int shield;

    void Start()
    {
        hp = maxHp;
        shield = maxShield;
        // Fill both bars
    }

    public void TakeDamage(int amount)
    {
        // The shield takes what it can; the rest comes off hp, down to 0. Then show both bars.
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games