Documentation

Unity Engine


User Manual

Script Reference

Unity Engine


OnTriggerExit(Collider)

Called when a collider stops touching a trigger collider.
Read time 2 minutesLast updated 7 days ago

Definition

OnTriggerExit()

public void OnTriggerExit(Collider collider)

Parameters

collider

Remarks

OnTriggerExit
is called during whichever iteration of the physics
FixedUpdate
loop Unity detects that a collider is no longer touching a trigger it was previously touching. Both GameObjects must contain a Collider component. At least one of the colliders must be a trigger collider and at least one must be a physics body collider. For more information, refer to OnTrigger events. Both the trigger and the collider that touches the trigger receive
OnTriggerExit
if they have implemented it. Trigger events are sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions. Deactivating or destroying either collider while they overlap doesn't cause an
OnTriggerExit
message to be sent. Physics backends report only that two shapes started or stopped overlapping, so Unity sends
OnTriggerExit
when the two colliders move apart. Deactivation and destruction don't produce an exit message, for two different reasons: - If you deactivate a collider, or the GameObject it belongs to, the message would report a collider that is no longer in the simulation. Deactivating a GameObject also stops its scripts from receiving messages at all, unlike disabling a
MonoBehaviour
, which still receives trigger events. - If you destroy a collider, there is nothing left to report to. The destroyed object can't receive the message, and the collider that
OnTriggerExit
supplies as its argument no longer exists. Unity could send
OnTriggerExit
in these cases by storing and maintaining a record of every overlapping pair in the scene, but maintaining that record costs CPU time and memory in every project, including projects that don't need this behavior. Handle these cases in your own scripts instead: record the colliders that enter each trigger, then treat a recorded collider as having exited when MonoBehaviour.OnDisable() or MonoBehaviour.OnDestroy() runs on it, or when it is no longer active. Record each collider's EntityId, and any data you need about it, while the collider is still alive. After Unity destroys a collider, the reference to it compares equal to
null
, so you can't read any values from it and you can't rely on it to report its own
EntityId
. For an example script, refer to OnTrigger events.
OnTriggerExit
can be a coroutine.

Examples

// Destroy everything that leaves the triggerusing UnityEngine;using System.Collections;public class ExampleClass : MonoBehaviour{ void OnTriggerExit(Collider other) { Destroy(other.gameObject); }}