How to create a health bar

Health.cs

Size: 4.76 KB

You need to login to download this file.

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.

 

  1. Add a UI image named "HealthBar"
    1. Give it a background image                     
  2. Add another UI image, this will be the bar
    1. Give it a square image
    2. Overlapse the background
    3. Give it a color
  3. Put image type on filled
    1. Fill method on Horizontal
    2. Fill origin on Left

  1. Add the Health.cs script, in this script you'll need to add these things:
    1. A public image variable
    2. public Image HealthBar;
    3. When applying damage or healing update the bar with this line of code
    4. HealthBar.fillAmount = healthPoints / 100f;

 

Blinking method

  1. 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;
  1. 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;
            }
        }
  1. 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

  1. Add 2 new variables
// New variable for the color of the health bar
    public Color lowHealthColor = Color.red;
    public float lowHealthThreshold = 25f;
  1. These will also be triggerd when the threshold value is passed

recommended