How to create a health bar
This guide will provide you with the basics to create a functional health bar with a blinking effect when passing a threshold value. The script is designed so that all additional functions (such as the blinking effect or turning red) can be disabled without encountering any issues.
- Add a UI image named "HealthBar"
- Give it a background image
- Add another UI image, this will be the bar
- Give it a square image
- Overlapse the background
- Give it a color
- Put image type on filled
- Fill method on Horizontal
- Fill origin on Left
- Add the Health.cs script, in this script you'll need to add these things:
- A public image variable
-
public Image HealthBar;
- When applying damage or healing update the bar with this line of code
-
HealthBar.fillAmount = healthPoints / 100f;
Blinking method
- Add these new variables
// Variable to determine if the health bar should blink
public bool blinkWhenLowHealth = false;
public float blinkInterval = 0.5f;
private bool isBlinking = false;
private Coroutine blinkCoroutine;
- Now add this if statement in de Update function to check if the health is below the threshold value
if (healthPoints <= lowHealthThreshold)
{
HealthBar.color = lowHealthColor; // Change the color of the health bar to red
// Start blinking if blinkWhenLowHealth is enabled and not already blinking
if (blinkWhenLowHealth && !isBlinking)
{
blinkCoroutine = StartCoroutine(BlinkHealthBar());
}
}
else
{
HealthBar.color = Color.green; // Reset the color of the health bar to green
// Stop blinking if health is above the threshold
if (isBlinking)
{
StopCoroutine(blinkCoroutine);
HealthBar.enabled = true;
isBlinking = false;
}
}
- Then add a blinking function for the effect
// Coroutine to make the health bar blink
IEnumerator BlinkHealthBar()
{
isBlinking = true;
while (true)
{
HealthBar.enabled = !HealthBar.enabled;
yield return new WaitForSeconds(blinkInterval);
}
}
Red color
- Add 2 new variables
// New variable for the color of the health bar
public Color lowHealthColor = Color.red;
public float lowHealthThreshold = 25f;
- These will also be triggerd when the threshold value is passed