Menu
CoddyTech

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 icon

Challenge

Easy

Fix the toll gate's method, then take the toll from cars.

  1. Press Play: the Console shows an error about the method. Change it to void OnTriggerEnter(Collider other).
  2. Inside, when other.CompareTag("Car"), add toll to collected and 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

Practice on your own: Unity playground