OnDestroy() called when I stop playing

I just stumbled upon OnDestroy() which seemed like a neat function to use instead of calling my own functions when things were destroyed. But the problem is that it gets called when I stop playing and I get this error: Some objects were not cleaned up when closing the scene. and my Hierarchy is filled with clones I have to manually delete.

Am I using it wrong? Or how can I avoid this?

What are you doing within OnDestroy? I’ve had this happen and its either when a uncaught exception occurs inside the OnDestroy or maybe if you Instantiate new objects withing OnDestroy during Application Quit ( end of editing session ). Not positive, but make sure you check the log for other errors behind that one. I’d avoid using OnDestroy for instantiating things like death particles, and continue using your own implementation for that stuff. You can tie into OnApplicationQuit to detect if the game is closing too if you need to modify something special for immanent destruction.

You’re right in that I’m instantiating an explosion. I’ve done it with my own function previously, but this looked like a simpler way and I thought I’d use it instead.

It wouldn’t be a problem if the explosions were instantiated before the application quit, but for some reason they come after and remain in the hierarchy.

Apparently it is not meant to be used in this way so I’ll just scrap it. :slight_smile:

Thanks for you reply.

Yea, no problem. OnDestroy is great for cleaning up data structures and stuff, But yea as far as effects you’d wanna keep that in your own implementation.

I made this:

using UnityEngine;
using UnityEditor;
using System.Collections;

[ExecuteInEditMode]

public class SceneCleaner : MonoBehaviour 
{
	void Update()
	{
		if (Application.isEditor  !EditorApplication.isPlaying)
		{
			GameObject[] objects = (GameObject[])FindSceneObjectsOfType(typeof(GameObject));
			foreach (GameObject o in objects)
				if (o.name.Contains("(Clone)"))
					DestroyImmediate(o);
		}
	}
}

Probably you can use Editor class instead, but I dont know how.

I put it on my scene object and now I can use Instantiate() inside OnDestroy(). I hope in the build Clones can’t be left in scene on scene destroy. Can’t they?

1 Like