TExcelTAD
Home › Unity with C# › Colliders, Triggers & the Collision Matrix

Colliders, Triggers & the Collision Matrix

A collider gives an object a physical shape. Rigidbodies use colliders to bounce off each other; triggers use them to detect overlap without any physical response. Which pairs of objects interact at all is decided by their layers.

Collider shapes

Collider Cost Use for
SphereCollider, CapsuleCollider, BoxCollider cheapest almost everything: characters (capsule), crates, pickups
MeshCollider (convex) medium odd-shaped dynamic objects (max 255 triangles)
MeshCollider (non-convex) expensive static level geometry only; can't be on a dynamic Rigidbody
TerrainCollider special terrains

Combine several primitive colliders on child objects instead of one detailed mesh collider: a car is a box plus four spheres. Give colliders a Physics Material for friction and bounciness.

Collision messages

Which messages you get depends on the two objects:

  1. At least one of them must have a Rigidbody (kinematic counts). Two static colliders never report anything.
  2. If either collider has Is Trigger ticked, you get OnTriggerEnter/Stay/Exit(Collider).
  3. Otherwise, if one body is dynamic (non-kinematic), you get OnCollisionEnter/Stay/Exit(Collision) with contact points and impulse.
csharp
using UnityEngine;

public class Mine : MonoBehaviour
{
    [SerializeField] float force = 12f, radius = 4f;
    static readonly Collider[] Hits = new Collider[16];              // reused buffer: no garbage per explosion

    void OnCollisionEnter(Collision collision)
    {
        if (collision.relativeVelocity.magnitude < 2f) return;       // ignore gentle touches
        ContactPoint contact = collision.GetContact(0);
        Explode(contact.point);
    }

    void Explode(Vector3 at)
    {
        // Non-alloc overlap query (see the raycasts lesson).
        int count = Physics.OverlapSphereNonAlloc(at, radius, Hits);
        for (int i = 0; i < count; i++)
        {
            Rigidbody rb = Hits[i].attachedRigidbody;
            if (rb != null) rb.AddExplosionForce(force, at, radius, 1f, ForceMode.Impulse);
        }
        Destroy(gameObject);
    }
}

public class Checkpoint : MonoBehaviour      // collider with Is Trigger ticked
{
    void OnTriggerEnter(Collider other)
    {
        if (other.TryGetComponent(out PlayerRespawn player))
            player.SetCheckpoint(transform.position);
    }
}

Triggers are perfect for pickups, checkpoints, damage zones, doors that open when you approach, and "is the player in range" checks. Put trigger colliders on a dedicated layer so they don't block raycasts by accident, or pass QueryTriggerInteraction.Ignore to queries.

The Layer Collision Matrix

Project Settings > Physics contains the Layer Collision Matrix: a triangle of checkboxes saying which layer pairs can collide at all. Unticking a pair is the cheapest way to make objects ignore each other, because the physics engine never even tests them. Typical setup:

  • PlayerProjectile doesn't collide with Player (no shooting yourself).
  • Pickup only collides with Player.
  • Ragdoll doesn't collide with Ragdoll.

From code, Physics.IgnoreLayerCollision(a, b) changes the matrix, and Physics.IgnoreCollision(colliderA, colliderB) ignores one specific pair. The matrix is just a 32 × 32 table of bits. The model:

csharp · try it yourself
using System;
using System.Collections.Generic;

string[] names = { "Default", "Player", "Enemy", "PlayerShot", "Pickup" };
var matrix = new CollisionMatrix(names.Length);   // starts with everything colliding
matrix.Ignore(1, 3);                               // Player  x PlayerShot
matrix.Ignore(3, 3);                               // PlayerShot x PlayerShot
for (int l = 0; l < names.Length; l++) if (l != 1) matrix.Ignore(4, l);   // Pickup only with Player

Console.Write("           ");
foreach (var n in names) Console.Write(
quot;{n[..4],5}"); Console.WriteLine(); for (int a = 0; a < names.Length; a++) { Console.Write(
quot;{names[a],-11}"); for (int b = 0; b < names.Length; b++) Console.Write(matrix.Collides(a, b) ? " x" : " ."); Console.WriteLine(); } var objects = new List<(string name, int layer)> { ("hero", 1), ("orc", 2), ("arrow", 3), ("coin", 4), ("rock", 0) }; int tested = 0, skipped = 0; for (int i = 0; i < objects.Count; i++) for (int j = i + 1; j < objects.Count; j++) if (matrix.Collides(objects[i].layer, objects[j].layer)) tested++; else skipped++; Console.WriteLine(
quot;pairs tested: {tested}, skipped by the matrix: {skipped}"); class CollisionMatrix { readonly uint[] rows; public CollisionMatrix(int n) { rows = new uint[32]; for (int i = 0; i < 32; i++) rows[i] = uint.MaxValue; } public void Ignore(int a, int b) { rows[a] &= ~(1u << b); rows[b] &= ~(1u << a); } // symmetric public bool Collides(int a, int b) => (rows[a] & (1u << b)) != 0; }
            Defa Play Enem Play Pick
Default        x    x    x    x    .
Player         x    x    x    .    x
Enemy          x    x    x    x    .
PlayerShot     x    .    x    .    .
Pickup         .    x    .    .    .
pairs tested: 6, skipped by the matrix: 4

In a busy scene, a well-set matrix removes a large share of the pair tests before the expensive shape checks begin.

Test yourself

Two objects with colliders but no Rigidbody overlap. Which message do they get?

  1. OnCollisionEnter
  2. OnTriggerEnter
  3. Nothing
  4. Both

How do you stop the player's bullets from ever hitting the player, as cheaply as possible?

  1. Check the tag in OnCollisionEnter and ignore it
  2. Put them on layers whose pair is unticked in the Layer Collision Matrix
  3. Make the bullets triggers
  4. Use a non-convex MeshCollider

Which collider should a dynamic, odd-shaped Rigidbody use?

  1. Non-convex MeshCollider
  2. Convex MeshCollider or several primitive colliders
  3. TerrainCollider
  4. No collider