Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity Editor: check if OnDestroy() method is called because the scene is closing

There are 2 cases when OnDestroy() is triggered in the Editor (the class should be marked with [ExecuteInEditMode] attribute):

  1. When the scene is closing and all objects are destroyed.
  2. When an object is deleted from the scene.

Is it possible to differentiate these two cases within OnDestroy()? I tried to subscribe to EditorSceneManager.sceneClosing to set the flag and then use it in OnDestroy() but this event didn't work. Are there any other options?

like image 589
Sergei Avatar asked Nov 15 '25 11:11

Sergei


1 Answers

A bit of an old question but it's the first result in Google so I thought I might share my approach.

void OnDestroy()
{
    if(gameObject.scene.isLoaded) //Was Deleted
    {

    }
    else //Was Cleaned Up on Scene Closure
    {

    }
}
like image 69
Moe Baker Avatar answered Nov 17 '25 09:11

Moe Baker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!