How to collide with some objects and ignore others? Unity – C#

by
Ali Hasan
c# collision-detection unity-game-engine

Quick Fix: In the Unity Inspector, assign different layers to objects that should collide and ignore. Modify the Layer Overrides for each collider to specify which layers it should interact with. For objects that should ignore collisions, enable the Is Trigger option.

The Problem:

Develop a solution to handle object interactions in a 2D physics simulation. The solution should allow for specific objects to trigger collision events without physically interacting or affecting the movement of the colliding object. Unlike ‘Physics2D.IgnoreLayerCollision,’ this solution should provide information about the colliding objects and their locations.

The Solutions:

Solution 1: Using Layer Overides

To discern collisions with specific objects and ignore others, employ Layer Overrides:

  1. Create a Layer for Ignored Objects: Designate a new layer for objects that should not interact but only trigger.

  2. Assign Layer to Objects: Set any objects that you wish to ignore collisions from to the newly created layer.

  3. Configure Main Object Colliders: Add two colliders to the object that will handle OnTriggerEnter/Exit/Stay events with specific objects while colliding with others.

  4. Configure First Collider:

    • Navigate to Layer Overrides.
    • Set "Exclude Layers" to the previously created layer.
    • This collider will engage with other objects while bypassing the layer of ignored objects.
  5. Configure Second Collider:

    • Enable IsTrigger.
    • In Layer Overrides, set "Exclude Layers" to all layers apart from the ignored objects layer.
    • This trigger collider will invoke OnTriggerEnter/Exit/Stay with qualified objects.
  6. Alternative Trigger Behavior:

    • If desired, you can swap the IsTrigger settings of both colliders to have all objects except the ignored layer trigger OnTriggerEnter/Exit/Stay events.

By following these steps, you can selectively handle collisions and triggers with specific objects while maintaining the ability to detect collisions with all other objects.

Q&A

How to make some objects call OnTriggerEnter/Exit/Stay and ignore collide with others, without using Physic2D.IgnoreLayerCollision?

Use Layer Overrides of the colliders. Create a layer for objects that will only trigger and not interact, then add 2 colliders to your main object.

Video Explanation:

The following video, titled "Unity 2D - Part 6: Ignore Layer Collisions - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

How to use layers to tell objects with colliders to ignore each other ... How to make a 2D Bow and Arrow with UNITY & C#!. Blackthornprod•87K ...