Novasloth

Games

I Thought I BROKE Unity #1

September 14, 2021

“Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)”

It first seemed like a good idea to create an Explode script, where I destroy the object that I attach the Explode script to using the Start method with a timer. After the time expires, when the object is destroyed, I utilize the OnDestroy method to create the appropriate explosion particle effects and handle any damage done by said explosion. This worked great and as expected!

BUT

If an explosion occurred and the effects were instantiated, but I stopped the game or closed the scene, Unity threw an error: “Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)”

Uhh…

“Yes, yes I did, Unity” - But what’s going on under the hood? I really thought I had come up with a nice and clever solution, and I didn’t fully understand why Unity was complaining.

Execution Order

Unity has an execution order that is important to understand. The OnDestroy method is also called upon the closure of a scene. So when exiting Play Mode, OnDestroy is called on all objects, and I am instantiating an object, but the scene is already closing; therefore, my new object is existing outside Unity’s cleanup call to OnDestroy (for those new objects created).

My Solution To The Solution

How did I fix this? I stopped creating an object in the OnDestroy method of the Explode script. I instead used the Update method to determine if the time has passed for an explosion to occur, instantiated my effects, and then instantly destroyed the object.

Another solution may be to use an isQuitting flag of some sort that is set in the OnApplicationQuit or OnDisable methods called when quitting your application, which are called before the OnDestroy method (OnDestroy is called last in a script’s lifecycle). Then in the OnDestroy method you can basically check, “Am I actually destroying my object or is the application closing?” and instantiate objects accordingly.

Unity’s manual on Execution Order: https://docs.unity3d.com/Manual/ExecutionOrder.html#WhenQuitting


Lee Barton

Written by Lee Barton.
Follow me on Twitter!

© 2025 Novasloth Games LLC. All Rights Reserved.