I instantiate a gameObject that immediately intersects with another gameObject. For both OnTriggerEnter is being fired.
When I now destroy one of them, OnTriggerExit is not being fired on the one that is still there. Is this a bug or does this count as intended?
I need to get notice of the fact that the intersection no longer persists, and OnTriggerExit would have been handy here.
This is almost certainly intended, as after you destroy the object there’s no Collider component left to pass to the other object’s OnTriggerExit function.
Here’s a simple way to handle it, by putting your exit trigger logic in Update where you can check whether the triggering object has been destroyed:
boolean triggered = false;
Collider other;
void OnTriggerEnter( Collider other )
{
triggered = true;
this.other = other;
// put other enter trigger logic here
}
void Update()
{
// check if we've been triggered but the other object has been destroyed
if ( triggered && !other )
{
// put exit trigger logic here
}
// put other update logic here
}
This bug seems to be back in Unity 2018.2.0f2, but I worked around it by implementing observers, so I notify the objects interested in the subject’s status, including when it’s destroyed.