Question About Destroy(gameObject)

Does it matter if Destroy(gameObject) is called at the top of the OnCollisionEnter method? I believe during lesson 64 on PlayClipAtPoint, Rick specifically put PlayClipAtPoint above Destroy(gameObject), so it could be called before the object and consequently, the script on the object, were destroyed. Here he calls level.BlocksDestroyed(); after calling Destroy(gameObject). Would this mean the block is destroyed before the rest of the script can run and decrease the remaining block count? I tried running the code shown and it still plays the sound even though it is calling to destroy the block that has the attached sound. If there was a significant amount of code after calling Destroy(gameObject) would all of it still run? Or would the object be destroyed before all of it could?

Thanks!

Destruction is really weird.

Destroy does not immediately destroy an object. (There is a method called DestroyImmediate but it’s not really supposed to be used – even the Unity manual warns against using it.)

Instead, when you call the Destroy method, an object gets “marked for destruction” and will be destroyed toward the end of the frame, together with a bunch of other stuff also marked for destruction. For the most part, this means a script will still finish running on a destroyed object.

Here’s the weird part. Some things in Unity – and I’m not sure what they are – check for destruction flags and will ignore an object that is marked for destruction. But yes, your script will still run. Things will still find it if they try to search for it. It may still get hits on raycasts – I’m not sure. It’s in a quasi-state of pseudo-destroyed, but it will be destroyed at the end of the frame after all scripts have finished running.

If that’s not fast enough for you, Sam came up with this neat trick of deactivating the object after destroying it. Deactivation happens immediately. And the combination of deactivating and flagging for destruction should be fairly close to as immediate obliteration* as we can get.

(Even “destroyed” objects are still in memory until the C# garbage collector does it’s thing in the background. It’s just destroyed as far as Unity is concerned.)

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms