Menu
CoddyTech

Enter and Exit

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 20 of 71.

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

Light the lamp while anything is in the loading bay.

  1. Add an int inBay; field. In Start(), set lamp.enabled = false;.
  2. In OnTriggerEnter, add 1 to inBay and set lamp.enabled = true;.
  3. In OnTriggerExit, take 1 off inBay, and switch the lamp off only when it is 0.

Press Play and push the crates in and out: the lamp stays on until the bay is empty. 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
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground