Trigger Colliders
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 15 of 63.
A collider with Is Trigger ticked is no longer solid: rigidbodies pass straight through it, and Unity reports the overlap instead, by calling OnTriggerEnter on the scripts of both objects. Finish lines, pickups and danger zones are triggers. In code, the box is the collider's isTrigger property.
This vault's alarm zone switches its collider to a trigger when the game starts, which is the same as ticking the box, and sounds the alarm when a guard walks in:
void Start()
{
GetComponent<Collider>().isTrigger = true;
}
void OnTriggerEnter(Collider other)
{
Debug.Log("Alarm!");
}Triggers follow the same rule as collisions: Unity only checks a pair when at least one of the two objects has a Rigidbody. Two objects without one never report each other, trigger or not. The guards patrol on a script, so each guard has a kinematic Rigidbody (Add Component, Rigidbody, Is Kinematic ticked): gravity and bumps leave it alone, and it still counts as a Rigidbody. Without the guards' Rigidbodies, a guard walks through the zone and the Console stays empty. Without isTrigger, the zone is a solid box, and a kinematic body never touches a collider that has no Rigidbody, so again nothing is logged. One Rigidbody in the pair is enough, on either object. The next lesson looks at other, the collider that came in.
Challenge
EasyThe Drone should fly a route through three rings, and each Ring should log its name and passed as the drone goes through it, for example Ring1 passed. Nothing works yet: the drone's script flies it with MovePosition, but nothing in the scene has a Rigidbody, and the rings are solid.
- In
Drone.cs, give the drone a Rigidbody when the game starts and keep it inbody. The drone must fly level along its route. One body on the drone covers all three rings. - In
Ring.cs, make each ring's collider a trigger when the game starts.
Press Play and watch the Console, then Check.
Try it yourself
using UnityEngine;
public class Ring : MonoBehaviour
{
void Start()
{
// Make this ring's collider a trigger
}
void OnTriggerEnter(Collider other)
{
Debug.Log(name + " passed");
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall