OnTriggerEnter
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 16 of 63.
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
EasyVehicles drive through the toll Gate, a trigger. The Driver script moves them and is finished. Write the gate's TollGate script:
- Every vehicle tagged
Carpaystoll(3): add it tocollectedand log the total,Toll: 3for the first car, thenToll: 6. - Anything else, such as the Cyclist, passes free and logs nothing.
Press Play first: the Console already shows a script error about the method as it is written. Fix it, 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
}
}
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