Gaming in Unity

11. Unity 2D Game 7 - Health Scripting


This guide will show how to code HealthBar to respond to in-game events!

Step 1 - Creating HealthUI Script

We need to create a HealthUI script.

At the top, we need to let Unity know we're using some different libraries. Add:

using System.Linq;
using UnityEngine.UIElements;

Declare two VisualElement variables:

VisualElement HealthBar;
VisualElement nextHeart;

Create an array of VisualElements:

VisualElement[ ] Hearts;

Inside void Start( ), we will get HealthBar and then store its hearts inside the VisualElements array:

HealthBar = GetComponent< UIDocument >().rootVisualElement.Q("Container");
Hearts = HealthBar.Children().ToArray();

Create a method called StartHealthBar to decide the amount of hearts at the start of the game based on currentHealth.

public void StartHealthBar(int currentHealth, int maxHealth) {
    for(int i = maxHealth-1; i >= currentHealth; i--) {
        Hearts[i].style.visibility = Visibility.Hidden;

Create a method called void AnimateHealthBar(bool increaseHealth)

Inside this method, add an if statement to detect whether health is increasing:

if(increaseHealth) {


Inside this, add a piece of code to find the next Heart and then make it visible.

nextHeart = Hearts.Where(x => !x.visible).FirstOrDefault(); = Visibility.Visible;

Add an else to detect if health is decreasing. Inside this, add code to make a heart invisible if health has decreased::

else {
    nextHeart = Hearts.Where(x => x.visible).LastOrDefault(); = Visibility.Hidden;


Attach this script to CharacterSprite.

Step 2 - Adjusting SpriteController Script

Import HealthUI into SpriteController and call StartHealthBar.


Add two if statements to SpriteController's ChangeHealth method.


Your health bar should now be fully functioning!

Created by: David Corish