0
0
UnityHow-ToBeginner ยท 3 min read

How to Use OnTriggerEnter in Unity: Simple Guide

In Unity, use the OnTriggerEnter(Collider other) method inside a script attached to a GameObject with a Collider set as a trigger. This method runs automatically when another Collider enters the trigger area, letting you respond to trigger events.
๐Ÿ“

Syntax

The OnTriggerEnter method has this syntax:

  • void OnTriggerEnter(Collider other): This method is called when another collider enters the trigger collider attached to the object.
  • Collider other: Represents the other collider that entered the trigger.

Make sure the GameObject has a Collider component with Is Trigger checked, and either this object or the other has a Rigidbody component.

csharp
void OnTriggerEnter(Collider other) {
    // Your code here
}
๐Ÿ’ป

Example

This example shows a script that prints a message when another object enters its trigger area.

csharp
using UnityEngine;

public class TriggerExample : MonoBehaviour {
    void OnTriggerEnter(Collider other) {
        Debug.Log("Trigger entered by " + other.gameObject.name);
    }
}
Output
Console output when another collider enters the trigger: "Trigger entered by [OtherObjectName]"
โš ๏ธ

Common Pitfalls

  • For OnTriggerEnter to work, the collider must have Is Trigger enabled.
  • At least one of the objects involved must have a Rigidbody component; otherwise, the event won't fire.
  • Using OnCollisionEnter instead of OnTriggerEnter for triggers is a common mistake.
  • Not attaching the script to the correct GameObject with the trigger collider can cause no events to fire.
csharp
/* Wrong: Collider without Is Trigger enabled */
// No OnTriggerEnter event will fire

/* Right: Collider with Is Trigger enabled and Rigidbody present */
void OnTriggerEnter(Collider other) {
    Debug.Log("Correct trigger event");
}
๐Ÿ“Š

Quick Reference

  • Collider with Is Trigger: Must be checked on the trigger collider.
  • Rigidbody: Required on at least one object involved.
  • Method signature: void OnTriggerEnter(Collider other)
  • Use for: Detecting when objects enter a trigger zone without physical collision response.
โœ…

Key Takeaways

Use OnTriggerEnter(Collider other) in a script on a GameObject with a trigger collider to detect trigger events.
Ensure the collider has Is Trigger enabled and at least one object has a Rigidbody component.
OnTriggerEnter runs automatically when another collider enters the trigger area.
Attach the script to the correct GameObject with the trigger collider to receive events.
Do not confuse OnTriggerEnter with OnCollisionEnter; triggers do not cause physical collisions.