Unity Basic Course: Managing Enemy Character Health

Unity is one of the most widely used engines in game development. It provides the flexibility and powerful features to create games on various platforms, but there are many elements to understand and handle. In this article, I will explain in detail how to implement and manage the health of enemy characters using Unity. This process assumes a basic knowledge of C# programming. Through this tutorial, strengthen the foundation of game development and enhance the fun and challenge of your game.

1. Understanding the Concept of Enemy Characters and Health

In games, the health points (HP) of enemy characters are a very important element. Health determines how much damage the player needs to inflict to defeat the enemy character. When the health reaches zero, the enemy character dies, which can trigger various reactions in the game. By managing health, you can adjust the difficulty of the game and enhance the user experience.

2. Project Setup

First, create a new Unity project and set up a 2D or 3D game environment. The setup process is as follows:

  1. Run Unity.
  2. Click the ‘New Project’ button.
  3. Specify the project name and path, and select a template (2D or 3D).
  4. Click the ‘Create’ button to create the project.

3. Creating an Enemy Character Script

Now let’s write a script to manage the health of the enemy character. Create a new C# script and name it `Enemy`. This script will include the enemy character’s health, damage values, and health reduction methods. The following code shows a basic enemy character health management script.


using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float maxHealth = 100f; // Maximum health
    private float currentHealth; // Current health

    void Start()
    {
        currentHealth = maxHealth; // Set initial health
    }

    // Method called when taking damage
    public void TakeDamage(float damage)
    {
        currentHealth -= damage; // Reduce health
        Debug.Log($"Enemy took {damage} damage. Current health: {currentHealth}");

        if (currentHealth <= 0)
        {
            Die(); // Handle death
        }
    }

    private void Die()
    {
        Debug.Log("Enemy died."); // Death message
        Destroy(gameObject); // Delete game object
    }
}

4. Implementing the Enemy Character Health System

Before implementing the health system, let's create an enemy character object that can interact with Unity's physics engine. Create or use a new 3D model for the enemy character and adjust its position. Follow the steps below.

  1. Right-click in the Hierarchy window and select ‘3D Object’ > ‘Cube’ to add the enemy character.
  2. Change the name of the Cube to ‘Enemy’.
  3. Drag the previously created `Enemy` script onto the Enemy game object to add it.

5. Handling Enemy Damage

Now we need to implement a system that can inflict damage on the enemy. We will add a method that is called when the player attacks the enemy. To do this, we will need to call the function that inflicts damage on the enemy character from the player management script.


using UnityEngine;

public class Player : MonoBehaviour
{
    public float damage = 20f; // Attack power
    public GameObject enemy; // Reference to the enemy character object

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) // Attack with spacebar
        {
            AttackEnemy();
        }
    }

    private void AttackEnemy()
    {
        if (enemy != null)
        {
            enemy.GetComponent().TakeDamage(damage); // Deal damage to the enemy
        }
    }
}

6. Displaying Enemy Character Health in UI

To visually display the enemy's health in the game, we can add a UI element. Unity allows for easy implementation of health bars using its UI system. Proceed with the steps below.

  1. Right-click in the Hierarchy window and select ‘UI’ > ‘Canvas’ to add a canvas.
  2. Right-click within the Canvas and select ‘UI’ > ‘Slider’. This slider will act as the health bar.
  3. Change the `Name` of the slider to ‘HealthBar’ and set the slider value to start from 1.

Then, add a method to update the health bar in the `Enemy` script.


using UnityEngine;
using UnityEngine.UI;

public class Enemy : MonoBehaviour
{
    public float maxHealth = 100f; 
    private float currentHealth; 
    public Slider healthBar; // Health bar slider

    void Start()
    {
        currentHealth = maxHealth; 
        if (healthBar != null)
        {
            healthBar.maxValue = maxHealth;
            healthBar.value = currentHealth;
        }
    }

    public void TakeDamage(float damage)
    {
        currentHealth -= damage; 
        Debug.Log($"Enemy took {damage} damage. Current health: {currentHealth}");

        if (healthBar != null)
        {
            healthBar.value = currentHealth; // Update health bar
        }

        if (currentHealth <= 0)
        {
            Die(); 
        }
    }

    private void Die()
    {
        Debug.Log("Enemy died."); 
        Destroy(gameObject); 
    }
}

7. Testing the Enemy Character Health System

All settings are complete. Now let’s test the game to see if the enemy character health system works correctly.

  1. Click the Play button at the top of Unity to run the game.
  2. The Cube set as the enemy character should be visible on the game screen.
  3. Press the Space key to inflict damage on the enemy and check that the health bar updates.
  4. Check that when the enemy’s health reaches zero, the enemy dies and disappears.

8. Implementing Additional Features

Although the basic health system implementation is complete, you can enhance it with additional features to create a more polished health system. For example:

  • Add different types of enemy characters: Introduce enemy characters with various maximum health and damage values to increase the game's diversity.
  • Health recovery system: Create enemy characters that recover health over time.
  • Death animation: Add an animation when the enemy character dies to enhance immersion.
  • Sound effects: Add sound effects when the enemy takes damage or dies to improve the game's quality.

9. Conclusion

In this tutorial, we learned how to manage the health of enemy characters in Unity. The health system is simple but essential to the game, and by implementing it properly, you can enhance the fun and challenge of the game. Expand the system with additional features and create your unique game. Game development using Unity offers limitless possibilities, and your creativity will be your most valuable asset.

Don’t be afraid to take your first steps into the world of game development. As you accumulate small successes and gain experience, you will be able to successfully lead larger projects in the future. I hope you continue to practice and deepen your learning based on what you learned in this tutorial today.