Health bars

Hal Brooks
3 min readDec 8, 2021

Objective: Add health bars to modular health system.

Health bars are implemented for the player and enemy using same Health script.

Health bars are UI sliders. Add a UI slider to the Enemy game object, which will create a Canvas, the slider renamed Enemy_Health_Bar and its child objects Background, Fill Area and Handle Slide Area, as shown below. Disable the Handle Slide Area by unchecking the box next to its name in the inspector.

The Canvas must be set up with World Space render mode. Only then adjust the rect transform position width and height and scale shown below to produce a small canvas just above the enemy.

Canvas on Enemy game object.

The Enemy_Health_Bar slider is set up as shown below with the position width and height dependent on the Canvas scale. Depending on the Enemy orientation select the direction as desired, here right to left. The goal is an aesthetically please bar over the Enemy.

Set up the Background as shown below, using a red color.

Set up the Fill as shown below, using a green color. Make sure to update Enemy overrides so the prefab also includes these changes.

Now modify the Health script, which was previously described, to add control over the slider. First add a [SerializeField] Slider _slider variable. Assign the _slider.maxValue to the _maxHealth. Initialize the _slider.value by calling the HealthBar() method.

Variable initialization in Health script on both Enemy and Player.

The _slider is assigned in the inspector and can be unique to each enemy. This give flexibility on the location and style of the slider.

Health component on Enemy with Slider assigned.

HealthBar() method simply assigns _slider.value to the currentHealth.

HealthBar() method sets the slider value in Health script.

The HealthBar() method is also called anytime the Damage() method is called as shown below.

A Player_Health_Bar can be set up in a completely different manner, but still using the script above. Duplicate the Enemy_Health_Bar and move the copy to be a child of the Canvas with the Cross_Hair, as shown below. Rename the copy to Player_Health_Bar.

This Canvas is uses a screen space overlay render mode so adjust the position, width, height and scale for the slider as shown below. The health bar should appear in the upper left of the screen, not over the player.

Player_Health_Bar component setup.

Assign this slider to the Health component on the Player game object using the inspector.

Health component of Player game object

This modular health system has flexibility to implement on any game object that can be damaged, and health bars provide a visual representation of the health of that object.

--

--