OnCollisionEnter() Ignore Layer Mask?

Is there a way of using OnCollisionEnter() but allowing the object with the script to pass through any objects within a layer mask? I’m creating a turret, which occasionally shoots the gun barrel it is coming out of, I feel that the barrel needs a collider, as if the player shoots at it, I want there to be an impact.

The below code shows that I am able to find if something has a layer after the collision, but this isn’t hugely important.

void OnCollisionEnter(Collision col)
    {
        if(col.gameObject.layer != 8)
        {
            Instantiate (explosion, gameObject.transform.position, new Quaternion ());
            ExplosionWork(col.contacts[0].point);
            Destroy(gameObject);
        }
        else
        {
            Debug.Log("Hit " + col.gameObject.name);
        }
    }

Is there a clause that can be put in the OnCollisionEnter() parenthesise that will prevent a layer being collided with?

Thanks.

If you want an object to pass through another, but still have a script reaction, you could use a trigger collider instead.

If you want two objects with normal colliders to not collider, you can set their layers to not collide in the physics layer.

Finally, if you need really fine-tuned control, the Physics API has a method named IgnoreCollision that allows you to turn off collision between two specific objects.

1 Like

Thank you @Baste , I have implemented IgnoreCollision and everything is now working as intended.

public Transform myParent;

void Start()
    {
        Physics.IgnoreCollision(myParent.GetComponent<Collider>(), GetComponent<Collider>());
    }