What is the most efficient way to understand that object exit collider without using OnTriggerExit()

Hello,

In one of my script I need to get colliding objects. I used classic method that uses List.

List<GameObject> collidingObjects = new List<GameObject>();
void OnTriggerEnter(Collider col)
{
    if (tags.Contains(col.gameObject.tag))
    {
        if (!collidingObjects.Contains(col.gameObject))
            collidingObjects.Add(col.gameObject);
    }
}

void OnTriggerExit(Collider col)
{
    if (collidingObjects.Contains(col.gameObject))
    {
        collidingObjects.Remove(col.gameObject);
    }
}

The problem is; sometimes colliding objects just dissapears without exiting collider bounds. So OnTriggerExit method isn’t called.

What is the most efficient method for my purpose?

Thanks

Vector3.Distance … if returned distance is more than a specific distance then you can think of it as if your character exits a collider

You could add an Event to the colliding object, that is invoked, when the object disappears. And in OnTriggerEnter the object with the list subscribes to that Event.

Something like this:

CollidingObject:

public UnityEvent onDisappear;

void Disappear() {
    //do stuff
    onDisappear.Invoke();
    onDisappear.RemoveAllListeners();
}

Object with the list:

void OnTriggerEnter(Collider col) {
    CollidingObject obj = col.GetComponent<CollidingObject>();
    if(obj != null && !collidingObjects.Contains(col.gameObject)) {
        collidingObjects.Add(col.gameObject);
        obj.onDisappear.AddListener(() => collidingObjects.Remove(col.gameObject));
    }
}