Menu
CoddyTech

Health Bars

Lesson 22 of 25 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

Show a health bar over each enemy once it is hit.

  1. In HealthBar, add [SerializeField] private Transform fill; and public void Show(float fraction): turn the bar on and set fill.localScale = new Vector3(fraction, 1f, 1f);.
  2. In Enemy, add [SerializeField] private HealthBar healthBar;; after TakeDamage takes health off, call healthBar.Show((float)health / data.maxHealth);.

Press Play: bars appear and shrink as the towers hit. 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
{
}

All lessons in Unity Game: Tower Defense

Practice on your own: Unity playground