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
EasyShow the knight's shield and health on two bars.
- Write
ShowBars():shieldBar.fillAmount = (float)shield / maxShield;, and the same forhealthBarwithhpandmaxHp. Call it inStart(). - In
TakeDamage, the shield takesMathf.Min(amount, shield)and the rest comes offhp, never below 0. Then callShowBars().
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
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 SwapPractice on your own: Unity playground