Search code examples
c#unity-game-enginecollision-detection

How to collide with some objects and ignore others? Unity


I want to collide with some objects and ignore others, and Physics2D.IgnoreLayerCollision is not suitable for me, because I want to know who and where I collided with, but without interacting.

Summary, I want to be in "isTrigger" mode with some objects, and collide with others.


Solution

  • To make some objects collide and others ignore you can use Layer Overrides of the colliders. First create a layer for the objects that will only trigger and not interact. Then set all of the objects you want to be only in trigger mode to the layer you created. After that you can add 2 colliders to your main object (the object that will call OnTriggerEnter/Exit/Stay with some and collide with others).

    In the first collider go to the Layer Overrides and set Exclude Layers to the layer you created. This collider is the collider that interacts with other objects and will ignore the objects in the layer you created.

    For the second collider enable IsTrigger and in the Layer Overrides set Exclude Layers to everything except the layer you created to prevent collision of other objects. This collider is the trigger collider and will call OnTriggerEnter/Exit/Stay when your new layer collides with it.

    If you want to make all objects except the selected layer call OnTriggerEnter/Exit/Stay, turn on IsTrigger in the first collider and turn off it in the second collider.

    And now you can use OnTriggerEnter/Exit/Stay it should only trigger with some of the objects in the specified layers. But I'm not sure if having 2 colliders in 1 object is good so you might consider transfering the collider that is not trigger to a child of that object.