Instantiate OnDestroy

I have a couple of objects that spawn a particle effect, when they are destroyed. Everytime I start the game from within Unity and then stop it, each object I have not destroyed during runtime spawns his death-effect and these linger in my hierarchy. Is there a way to prevent this from happening?

Script:
function OnDestroy() {
Instantiate(object, position, rotation);
}

The problem is that OnDestroy gets called when the objects get cleaned up when you go back to the editor! If you don't want this to happen, you will have to spawn your death effects another way.

Feared as much...luckily it is no big deal to pull the Instantiate out of OnDestroy and put it right before I destroy the object itself.

That sounds like you use ExecuteInEditMode... Are you sure that you need the scripts functionality at edit time? You have to be careful with ExecuteInEditMode, it can break your whole scene when used wrong. Only use it when you really need it and you know what you're doing...

No no..it is as syclamoth said. When I end playmode, all objects get cleared and call their OnDestroy function. I didn't even know about ExecuteInEditMode until now :D

1 Answer

1

Make use of the fact that on each MonoBehaviour OnApplicationQuit() is called before OnDestroy():

`
private bool isQuitting = false;

void OnApplicationQuit()
{
    isQuitting = true;
}

void OnDestroy()
{
    if (!isQuitting)
    {
        //your code
    }
}

`

Cheers, Tommy

Thanks. That works.

Ohh, good one!

Much thanks ;)

thanks for the simple answer :)

The diagram at the bottom here seems to suggest the opposite: http://docs.unity3d.com/Manual/ExecutionOrder.html It shows OnDestroy is before OnApplicationQuit. Is it wrong?