I found out that objects seem to be able to trigger a collision event in the same frame after they are destroyed.
In my case the Destroy() call is made in Start() where objects are identified via Physics.OverlapSphere() in a certain radius.
But in OnTriggerEnter() they are still registered after they are destroyed.
Is there a way to make sure they are destroyed right away and can not take part in the physics calculation anymore?
Hi, yes, objects destroyed by Destroy() are not destroyed immediately. Destruction happens “after all frame updates” (Unity - Manual: Order of execution for event functions)
Unity does not recommend to use DestroyImmediate() so one way is to disable collider components before calling Destroy, or disable the whole GameObject using SetActive( false ) just before calling Destroy() (it seems to be a good practice to do so anytime Destroy() is used)
Destroy indeed only lists the passed object for destruction at the end of the frame. But while
DestroyImmediate exists, I think that is not the problem, since physics events don’t happen between Start and the actual destruction phase.
I think that what happens is this, and in this order:
- Physics events happen
- Start is being called, Destroy is invoked
- Object gets destroyed
So merging 2 and 3 by using DestroyImmediate wouldn’t help, not to mention Destroy is supposed to be used for a reason.
Instead, maybe have the objects be initially inactive. Sure, they need the colliders for your OverlapSphere, but perhaps you can deactivate the script that reacts to OnTriggerEnter for the first frame.