Health Bar Doesn't Go Down When Colliding With Enemy

I was following a few tutorials and now I have a health bar on top of the screen. The bar goes down when I jump (I wanted to test if it works). And the player dies when the health bar is empty. How can I make it so the health bar goes down when it touches an enemy?

Here is my script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Health : MonoBehaviour

{
public int maxHealth = 100;
public int currentHealth;

public HealthBar healthBar;
// Start is called before the first frame update
void Start()
{
    currentHealth = maxHealth;
    healthBar.SetMaxHealth(maxHealth);
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        TakeDamage(10);
    }
    if (currentHealth <= 0)
        Destroy(gameObject);

}

void TakeDamage(int damage)
{
    currentHealth -= damage;

    healthBar.SetHealth(currentHealth);
}

}

You can use FillAmount in your SetHealth method. So that the fill of the image that represents the health is directly connected to the ‘currentHealth’ variable. You can follow this tutorial if it is not already this you are following.

Add the method OnCollisionEnter (or OnTriggerEnter if your Collider is set as trigger) and call TakeDamage inside it, also you may want to check collision.gameObject.tag inside it to filter only the collisions with enemy gameobjects else you’ll take damage also colliding with walls etc.

Also I see that you’re checking whether currentHealth reaches 0 inside your Update, that’s not necessary since the only line of code where you decreases currentHealth is in TakeDamage so I’d move that statement inside TakeDamage after the call to healthBar.SetHealth

A better approach to your TakeDamage:

void TakeDamage(int damage)
{
     // The following line ensures that currentHealth is minimum 0 (avoid negative number)
     currentHealth = Mathf.Max(0, currentHealth - damage);
     healthBar.SetHealth(currentHealth);
     if (currentHealth == 0)
          Destroy(gameObject);
}