ScriptReference/MonoBehaviour.OnDestroy #365
Replies: 2 comments
-
Comment by It's not mentioned here, but instantiating a GameObject in OnDestroy (like spawning debris, gibs, other effects) will result in the error: "Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)" when you stop the game or change scene. So I don't think it can be recommended for this purpose. Instead it's probably a better idea to create a custom OnDeath() or similar public method which instantiates the desired objects and then destroys itself. |
Beta Was this translation helpful? Give feedback.
-
If you need to differentiate between an object being destroyed during gameplay (e.g., you called Destroy on it) vs. destruction due to scene unloading, you can check if the scene that the object belonged to is loaded. void OnDestroy()
{
// was destroyed
if(gameObject.scene.isLoaded)
{
}
// was deleted by scene unload
else
{
}
} For example, if its scene is loaded, then it's just the object being destroyed; you'll likely want to unsubscribe from events or whatever other clean-up stuff you need to do. If not, then the entire scene is getting destroyed, so you don't/can't do any of that unless you know that they're either not a part of the Unity lifecycle or are a part of a separate scene that isn't unloaded yet. I originally learned this via Moe Baker on Stack Overflow. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
ScriptReference/MonoBehaviour.OnDestroy
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDestroy.html
Beta Was this translation helpful? Give feedback.
All reactions