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
EasyLight the lamp while anything is in the loading bay.
- Add an
int inBay;field. InStart(), setlamp.enabled = false;. - In
OnTriggerEnter, add 1 toinBayand setlamp.enabled = true;. - In
OnTriggerExit, take 1 offinBay, 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
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