Menu
CoddyTech

Health Bars

Lesson 16 of 18 in Coddy's Unity Game: Tower Defense course.

A bar over each enemy shows the health it has left. In the enemy prefab it is two thin cubes: a dark background and a green fill in front of it. The fill's width is the health left divided by the full health, a number from 0 to 1, and scaling the fill's x by it makes it shorter. A cube scales around its centre, though, so the fill would shrink toward the middle from both ends. The fill sits under an empty pivot object at the bar's left edge, and the script scales the pivot instead: everything under it shrinks toward that edge, and the bar empties from the right.

The fraction must be worked out in floats. health / data.maxHealth divides two ints, and C# drops the fraction of an int division: 6 / 9 is 0, so the bar would read empty after the first hit. Casting one side first, (float)health / data.maxHealth, gives 0.67. A water tank whose level grows upward from its pivot at the bottom:

float level = (float)water / capacity;
waterPivot.localScale = new Vector3(1f, level, 1f);

A full bar tells the player nothing, so the bar starts hidden: the prefab has it inactive, and the first hit turns it on. An inactive object gets no Update, but its methods can still be called. Each enemy is its own copy of the prefab, with its own bar.

challenge icon

Challenge

Hard
  1. In HealthBar, add a serialized Transform fill (the Inspector gives the bar's FillPivot) and public void Show(float fraction), which turns the bar's GameObject on and scales fill to fraction along x.
  2. In Enemy, add a serialized field healthBar (a HealthBar). Every time TakeDamage takes health off, show the health left as a fraction of maxHealth.

Each enemy prefab has its bar: inactive, with the HealthBar script, and the fill under a pivot at the left edge. Press Play and watch the bars as the towers fire, then Check.

Try it yourself

using UnityEngine;

// Comes later: the bar over an enemy that shows the health it has left.
public class HealthBar : MonoBehaviour
{
}
quiz iconTest yourself

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

All lessons in Unity Game: Tower Defense