Called when a collider stops touching a trigger collider.
public void OnTriggerExit(Collider collider)
is called during whichever iteration of the physics
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
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
message to be sent. Physics backends report only that two shapes started or stopped overlapping, so Unity sends
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
, 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
supplies as its argument no longer exists. Unity could send
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
, so you can't read any values from it and you can't rely on it to report its own
. For an example script, refer to
OnTrigger events.
can be a coroutine.
// Destroy everything that leaves the triggerusing UnityEngine;using System.Collections;public class ExampleClass : MonoBehaviour{ void OnTriggerExit(Collider other) { Destroy(other.gameObject); }}