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
EasyThe 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:
hpstarts atmaxHp(80) andshieldatmaxShield(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 offhp, which never goes below 0.- After each hit, both bars show what is left:
shieldBarthe shield out ofmaxShield,healthBarthe hp out ofmaxHp.
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.
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap