Menu
CoddyTech

Enter and Exit

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 19 of 63.

A trigger sends two more messages. OnTriggerExit(Collider other) runs once, on the physics step when the overlap ends, however it ends. OnTriggerStay(Collider other) runs on every physics step while the overlap lasts, 50 times a second by default, like FixedUpdate(). All three take the same Collider.

This updraft lifts whatever floats inside it and reports when it leaves:

public float lift = 15f;

void OnTriggerStay(Collider other)
{
    other.attachedRigidbody.AddForce(Vector3.up * lift);
}

void OnTriggerExit(Collider other)
{
    Debug.Log(other.name + " left the updraft");
}

A force belongs in a physics step, so OnTriggerStay suits it: the push is applied once per step for as long as the ball is inside, and stops the moment it leaves. The updraft has no Rigidbody, so every visitor must have one, and attachedRigidbody is never null here. For an amount per second inside OnTriggerStay, multiply by Time.deltaTime, which during a physics step is the step's length, 0.02. Each visit gives one OnTriggerEnter and, later, one OnTriggerExit for the same collider.

challenge icon

Challenge

Easy

The yellow Bay painted on the warehouse floor is a trigger, and lamp is the warning light on the post beside it. Write LoadingBay so the lamp shows whether anything is in the bay:

  • When the game starts the bay is empty, so the lamp is off (lamp.enabled = false).
  • While at least one object is in the bay, the lamp is on.
  • When the last object leaves, the lamp goes off again.

Two crates and the player can all be in the bay at once, so one leaving does not mean the bay is empty. Press Play and push the crates in and out with the arrows, then Check.

Try it yourself

using UnityEngine;

public class LoadingBay : MonoBehaviour
{
    public Light lamp;

    // The lamp is on while anything is in the bay, and off when the bay is empty
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay