Trigger Colliders
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 15 of 71.
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
EasyFly the drone through the rings, and let each ring report it.
- In
Drone.cs'sStart(), setbody = gameObject.AddComponent<Rigidbody>();andbody.isKinematic = true;, so it flies level. - In
Ring.cs'sStart(), setGetComponent<Collider>().isTrigger = true;.
Press Play: the drone flies through, and the Console shows Ring1 passed, Ring2 passed and Ring3 passed. 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");
}
}
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground