OnTriggerEnter
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 16 of 71.
void OnTriggerEnter(Collider other) runs once, on the physics step when another collider starts to overlap a trigger. other is that collider, so other.name, other.gameObject and other.CompareTag("Player") tell you what came in. Unity calls it on the scripts of both objects: on the trigger, other is the visitor, and on the visitor, other is the trigger.
This finish line reacts to the player and to nothing else, so a ball that rolls across it logs nothing:
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Debug.Log(other.name + " crossed the finish line");
}
}The parameter must be a Collider. Written as void OnTriggerEnter(Collision collision), the script still compiles, because to C# it is an ordinary method. Unity checks the parameter itself, logs a Script error: OnTriggerEnter that says This message parameter has to be of type: Collider, and never calls the method. Collision belongs to OnCollisionEnter, where two solid bodies meet at a contact point. A trigger has no contact to report, only the collider, so it gets a Collider.
Challenge
EasyFix the toll gate's method, then take the toll from cars.
- Press Play: the Console shows an error about the method. Change it to
void OnTriggerEnter(Collider other). - Inside, when
other.CompareTag("Car"), addtolltocollectedand log"Toll: " + collected. The cyclist passes free.
Press Play: the Console shows Toll: 3, then Toll: 6. Then Check.
Try it yourself
using UnityEngine;
public class TollGate : MonoBehaviour
{
public int toll = 3;
int collected;
void OnTriggerEnter(Collision collision)
{
// Cars pay the toll; anything else passes free
}
}
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