OnTriggerEnter and Layer mask. Need help

I have a script that has OnTriggerEnter, but I wanted it to ignore some layers that collides with, so I tried using layer mask. It doesn’t seem to work and I was hoping someone can help me? Heres the script till now:

public LayerMask layerMask;
void OnTriggerEnter(Collider c){
if(c.gameObject.layer == layerMask){
Instantiate(projectileCorpse, transform.position, transform.rotation);
Destroy(gameObject);
}
}

I have no errors showing on the code but it doesn’t seem to work.

I know I’m 6 years late but I’m just gonna leave this here for anyone else who finds himself stuck in this situation.

ATTENTION: This works in Unity 5, but probably not in any version before that.

While working in my 2D game, I wanted a projectile to be destroyed when colliding with a certain group of objects.
After a lot of searching, I got to write this:

    public LayerMask mask;


    void OnCollisionEnter2D(Collision2D other)
    {
        if(((1 << other.gameObject.layer) & mask) != 0)
        {
            Destroy(this.gameObject);
        }
    }
  • You set your LayerMask at the top and pick your the layers you want in the Inspector.
  • Your if statement will be “if(((1 << other.gameObject.layer) & nullLayermask) != 0)”.
  • This lets the System check the other Game Object’s Layer Number and if the Layer Number is in your Layermask, then it will proceed to run the code you place inside it.

You can even use 2 layermasks if you place the other Mask in an “else if” statement.

Here’s my full code if anyone wants to see an example:

public LayerMask nullLayermask;
    public LayerMask activeLayermask;

    void OnCollisionEnter2D(Collision2D other)
    {
        //if (other.gameObject.layer == nullLayermask)
        if(((1 << other.gameObject.layer) & nullLayermask) != 0)
        {
            Destroy(this.gameObject); //Destroy Self
        }
        else if (((1 << other.gameObject.layer) & activeLayermask) != 0)
        {
            //Hurt Other GameObject
            //Code pending
        }
    }
6 Likes

Thanks for this, I’m glad you added it. I ended up using the layer collision matrix in my project, but for alternative approaches this link has another way to go about it.

https://stackoverflow.com/questions/64798731/how-do-i-find-out-he-layer-of-a-collider