Menu
CoddyTech

Health Bars

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

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

Show the knight's shield and health on two bars.

  1. Write ShowBars(): shieldBar.fillAmount = (float)shield / maxShield;, and the same for healthBar with hp and maxHp. Call it in Start().
  2. In TakeDamage, the shield takes Mathf.Min(amount, shield) and the rest comes off hp, never below 0. Then call ShowBars().

Press Play and walk onto the spikes: the shield bar empties first. 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.
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground