Course contentsShow
← Unity Game Development
Lesson 165 of 8283. Physics and InteractionFree lesson

Detecting Triggers with Specific Layer Masks

Refine trigger detection scripts to ignore irrelevant objects by filtering incoming interactions based on their assigned physics layers.

In this lesson, you will learn how to refine your trigger logic so your scripts only react to specific types of objects using Layer Masks.

The Problem with Basic Triggers

Up until now, you have used OnTriggerEnter to detect any collider that enters your trigger zone. However, a game world is crowded—you might have projectiles, items, scenery, and enemies all overlapping. If your "Door" trigger reacts to everything that walks inside, your game logic will quickly become messy or bug-prone.

Filtering with Layer Masks

Instead of checking the object's name or tag (which can be slow and brittle), we use Layer Masks. A Layer Mask is essentially a bitmask that tells Unity, "I only care about objects assigned to these specific layers."

By checking the layer of the incoming object against a mask defined in your script, you ensure that your code only runs for the intended interactions.

Implementation Example

To implement this, define a LayerMask variable in your script. This allows you to select the target layers directly in the Inspector.

using UnityEngine;

public class TriggerFilter : MonoBehaviour
{
    [SerializeField] private LayerMask detectionMask;

    private void OnTriggerEnter(Collider other)
    {
        // Use bitwise logic to check if the layer is within our mask
        if ((detectionMask.value & (1 << other.gameObject.layer)) > 0)
        {
            Debug.Log("Valid object detected: " + other.name);
            // Perform your specific interaction logic here
        }
    }
}

How it Works

  1. detectionMask.value: This retrieves the integer representation of the layers you selected in the Inspector.
  2. 1 << other.gameObject.layer: This bit-shifts the number 1 to the position of the incoming object's layer index.
  3. Bitwise & (AND): We compare the two values. If the result is greater than zero, it means the incoming object belongs to one of the layers allowed by your mask.

This approach is highly efficient and keeps your physics code clean by ignoring irrelevant collisions before any expensive logic is executed.

Key Takeaway: Use Layer Masks to filter trigger events, ensuring your scripts only process interactions with intended object types while ignoring the rest of the game scene.