C# OnTriggerEnter2D. How to only trigger when touching a specific collider and used for collision

Hi everyone,

So I have this weird problem I ran into and have no clue how to work around it. I basically want my character/enemies to be able to collide with everything but not set off a trigger.

My script:

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

public class DamageHandler : MonoBehaviour {

    int health = 1;

    void OnTriggerEnter2D(Collider2D ){
        Debug.Log ("Trigger!");

        health--;

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

    void Die(){
        Destroy(gameObject);
    }
}

As you can see this would kill anything that has the script attached to it if they touch another collider. So if my enemies run into a wall they would die. I have though about using layers but then they pass through the walls etc. So is there any way I can modify this so they wont die when touching walls and be able to collide with it even when set to IsTrigger?

Because you’re given the collider than produces the trigger event, you can examine that collider for any property you’re curious about.

  • If you’ve setup a damage-dealing layer, then you can check collider.gameObject.layer to see if it is in that layer. If so, do damage, if not, do nothing. But the layers still need to be marked as interacting with each other or else you’d get the no-collision behavior that you described.

  • You can likewise use tags instead of layers, if you just need to query if collider is marked as a damage dealer.

  • My favorite: You can create a DamageDealer MonoBehaviour and attach that to any damage-dealing objects. In the OnTriggerEnter2D() event, check collider.GetComponent(). If it returns a non-null value, then do damage. Even better, you can use the object it returns to check how much damage to do, if it is a special type of damage, or whatever else you can dream up.

A couple other notes:

  • You never gave your Collider2D parameter a name, which is I guess is perfectly legal syntax for C#, but kinda hides the fact that you have an input object that you can use and examine.
  • As for triggers eliminating actual collisions with walls and such, I’m pretty certain you can add multiple colliders and mark some as triggers and not others. Sometimes, for complex transformation reasons, I’ve had to go so far as to add a child game object with a trigger collider, though that forces you to put a special script on the child object that knows how to catch the trigger event and communicate it back up to the parent. (There may be a better Unity-magic way of doing this that I’m just unaware of.)

As a parameter…
void OnTriggerEnter2D(Collider2D col); (here,"col"refers to the object to which the script is attached)

Now inside,
Destroy(col.gameobject); (here,“col.gameobject”,refers to which the object is getting collided,and hence that collided object gets destroyed)

Hope this helped you…!!!