Triggers and collisions help your game know when objects touch or overlap. They let your game react to these events, like opening a door or stopping a character.
Trigger vs collision detection in Unity
public class Example : MonoBehaviour { void OnTriggerEnter(Collider other) { // Code runs when another object enters this trigger } void OnCollisionEnter(Collision collision) { // Code runs when this object collides with another } }
OnTriggerEnter requires the collider to be set as a Is Trigger in Unity.
OnCollisionEnter requires both objects to have colliders and at least one to have a Rigidbody.
void OnTriggerEnter(Collider other) {
Debug.Log("Player entered the trigger area.");
}void OnCollisionEnter(Collision collision) {
Debug.Log("Player hit a wall.");
}void OnTriggerEnter(Collider other) {
if (other.CompareTag("Collectible")) {
Debug.Log("Collected an item!");
}
}void OnCollisionEnter(Collision collision) {
if (collision.gameObject.CompareTag("Enemy")) {
Debug.Log("Player bumped into an enemy!");
}
}This script prints messages when the object either triggers or collides with another object. Attach it to a GameObject with a Collider. Set the Collider's Is Trigger on to test triggers, or off to test collisions.
using UnityEngine; public class TriggerVsCollisionExample : MonoBehaviour { void OnTriggerEnter(Collider other) { Debug.Log("Trigger detected with " + other.name); } void OnCollisionEnter(Collision collision) { Debug.Log("Collision detected with " + collision.gameObject.name); } }
Time complexity: Both trigger and collision detection run efficiently within Unity's physics engine.
Common mistake: Forgetting to set Is Trigger for triggers or missing Rigidbody on objects for collisions.
Use triggers when you want to detect overlap without blocking movement. Use collisions when you want physical interaction and blocking.
Triggers detect when objects overlap without physical blocking.
Collisions detect physical contact and block movement.
Set Is Trigger for triggers; use Rigidbody and colliders for collisions.