Take health from enemy

So…In my game, my fireBall particlesystem has to take as much health (stored in enemy) as there is damage (stored in fireBall) from enemy. The collision happens, but no health gets taken away.

public class fireball : MonoBehaviour {
    public float speed=1f;
    public float damage = 25f;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
transform.Translate(0,0,speed);

}
void OnParticleCollision(GameObject other)
{
    if (other.transform.tag == "Enemy")
    {
        
        if (other.GetComponent<removeHealth>())
        {
            Debug.Log("collided");
            other.GetComponent<removeHealth>().health -= damage;
        }
    }
}

}

Enemy has this script.

public class removeHealth : MonoBehaviour {
    public float health = 100f;
    void Start()
    {
       gameObject.tag = "Enemy";
    }
    void Update()
    { }

    public void RemoveHealth()
    {
        if (health < 1)
        {
            Debug.Log("YEY");
            Destroy(gameObject);
        }
    }
}

If your enemy has multiple GameObjects as children, the ball may be colliding with one of the parts that doesnt contain the script. Try the GetComponentsInChildren function or the GetComponentsInParent method. I had the same problem in my game.

The RemoveHealth method is not being called so call it from Update() of the enemy or call it from fireball.
Also, I would rather make health private and reduce it through a public method.

KidRIgger’s answer works, however it is quite inefficient. You are running RemoveHealth every update, which is not necessary. You should run it only when health is deduced. Even your function name says “Remove Health” not “CheckHealth”.

You should instead call the RemoveHealth() function only when collision was detected. And in RemoveHealth() function reduce health and then check if health is below 1. If it is, destroy the object.

So in fireball class:

void OnParticleCollision(GameObject other)
 {
     if (other.transform.tag == "Enemy")
     {
         
         if (other.GetComponent<removeHealth>())
         {
             other.GetComponent<removeHealth>().RemoveHealth(damage);
         }
     }
 }

And in removeHealth class change the function RemoveHealth() to accept a float paramater “damage”.

public void RemoveHealth(float damage)
     {
         health -= damage;
         if (health <= 1)
         {
             Destroy(gameObject);
         }
     }

Also, it is quite common and a good habit to write class names in capital letters. So your class should be called RemoveHealth instead.