Enemy Taking Damage on All collisions, not just Tag

Hey Everyone,

My enemy is supposed to take damage when he collides with my bullet, which has the tag “Bullet”.
This does work. But in addition, if my enemy collides with a wall it also takes damage. Even though the wall has a different tag.

How can I get my enemy to only take damage when colliding with “Bullet”?

void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Bullet")
        Debug.Log("damage one!");
        health --;

    }

You are missing {} around the code relevant to the if statement. When you do not include {} for your if statements then only the next line is encapsulated by the if statement, and every other line will run regardless of whether it is meant to be part of the if condition or not.
For example, your code actually evaluates to the equivalent of the following:

void OnTriggerEnter2D(Collider2D other)
{
       if (other.tag == "Bullet")
       {
              Debug.Log("damage one!");
       }
       health --;
}

You should change your code to be this:

void OnTriggerEnter2D(Collider2D other)
{
       if (other.tag == "Bullet")
       {
              Debug.Log("damage one!");
              health --;
       }
}
2 Likes

Oh man now I feel dumb! Thanks for the help, this fixed it.