Creating an Enemy Life Bar in Unity using C#

Creating an Enemy Life Bar in Unity using C#

  1. In a new Unity project and create a UI Image component to the scene. This image will serve as the background for the enemy life bar.

  2. Create a new C# script and name it "EnemyLifeBar." Attach the script to the UI Image game object.

  3. In the EnemyLifeBar script, create a public float variable named "currentHealth" and set it to 100. This variable will be used to store the current health of the enemy.

  4. Create a new UI Slider component and set its "Fill Area" to the UI Image game object. This will make the slider fill the image, creating the appearance of a life bar.

  5. In the EnemyLifeBar script, create a public function named "UpdateHealth" that takes in a float value as a parameter. This function will be used to update the current health of the enemy.

  6. Inside the UpdateHealth function, set the "currentHealth" variable to the value passed in as a parameter. Then, set the "value" property of the UI Slider component to the current health divided by 100 (to convert it to a percentage value between 0 and 1).

  7. In a separate script or in the Update function of the EnemyLifeBar script, call the UpdateHealth function and pass in a new value to update the enemy's health.

  8. Test the enemy's life bar by running the Unity project and observing the changes in the life bar's progress as the UpdateHealth function is called with different values.

1.  Example of basic code:

using UnityEngine;
using UnityEngine.UI;

public class EnemyLifeBar : MonoBehaviour
{
    public float currentHealth = 100;
    public Slider healthBar;

    public void UpdateHealth(float health)
    {
        currentHealth = health;
        healthBar.value = currentHealth / 100;
    }
}


In this code, the EnemyLifeBar script is attached to the UI Image game object and the healthBar variable is linked to the UI Slider component. The UpdateHealth function updates the currentHealth variable and the value of the healthBar Slider component.

this is a basic code, you can add more functionality like if currentHealth reach zero the gameObject with the script attached will be destroyed and other functionalities, you can also adjust the color of the bar depending on the health or add sound effects when the health decrease or increase.

2.  Example of advanced code with additional functionality:


using UnityEngine;
using UnityEngine.UI;

public class EnemyLifeBar : MonoBehaviour
{
    public float maxHealth = 100;
    public float currentHealth;
    public Slider healthBar;
    public Image healthBarFill;
    public Color lowHealthColor = Color.red;
    public Color fullHealthColor = Color.green;
    public GameObject deathEffect;
    public AudioClip damageSound;
    public AudioClip deathSound;
    public float damageSoundVolume = 0.5f;
    public float deathSoundVolume = 1f;

    private AudioSource audioSource;

    void Start()
    {
        currentHealth = maxHealth;
        healthBar.maxValue = maxHealth;
        healthBar.value = currentHealth;
        healthBarFill.color = fullHealthColor;
        audioSource = GetComponent<AudioSource>();
        if(audioSource == null)
        {
            audioSource = gameObject.AddComponent<AudioSource>();
        }
    }

    public void TakeDamage(float damage)
    {
        currentHealth -= damage;
        healthBar.value = currentHealth;
        UpdateHealthBarColor();
        if(currentHealth <= 0)
        {
            Die();
        }
        else
        {
            if(damageSound != null)
            {
                audioSource.PlayOneShot(damageSound, damageSoundVolume);
            }
        }
    }

    public void UpdateHealth(float health)
    {
        currentHealth = health;
        healthBar.value = currentHealth;
        UpdateHealthBarColor();
        if(currentHealth <= 0)
        {
            Die();
        }
    }

    void UpdateHealthBarColor()
    {
        float healthPercent = currentHealth / maxHealth;
        if(healthPercent <= 0.3f)
        {
            healthBarFill.color = lowHealthColor;
        }
        else
        {
            healthBarFill.color = fullHealthColor;
        }
    }

    void Die()
    {
        if(deathEffect != null)
        {
            Instantiate(deathEffect, transform.position, transform.rotation);
        }
        if(deathSound != null)
        {
            audioSource.PlayOneShot(deathSound, deathSoundVolume);
        }
        Destroy(gameObject);
    }
}

       


This script includes several new features:

  • A maxHealth variable to store the maximum health of the enemy
  • A healthBarFill variable to store the Image component that fills the Slider to change its color
  • A lowHealthColor variable to store a color to change the health bar fill color when the health is low
  • A deathEffect variable to store a GameObject that will be instantiated when the enemy dies
  • A damageSound variable to store an AudioClip that will be played when the enemy takes damage
  • A deathSound variable to store an AudioClip that will be played when the enemy dies
  • A damageSoundVolume and deathSoundVolume variable to adjust the volume of the sound effects
  • An AudioSource component that will play the sound effects

The script has been updated to include additional functionality such as:

  • A TakeDamage function that reduces the currentHealth by the passed in damage value and updates the health