Callback for just before scene is unloaded

I have a global object pool that is in the “DontDestroyOnLoad” scene, and it has a reference to every object that has pulled from it, and thus has the ability to recall all these objects back into it. When a scene unloads, I need this to happen before the scene is unloaded, without having to manually call them back each time.

I know there is SceneManager.sceneUnloaded, but that is called after GameObjects have already been destroyed, so it’s too late. Is there any callback for just before the scene has been unloaded, so I could grab them before they are destroyed?

Your manager should have a list of objects and you can iterate that before you call the scene to unload. However, what I do is parent the objects to an object that isn’t in the scene that you are unloading. That way, the scene can be destroyed and the game objects don’t exist in the scene anyway (if they are pooled).

Ah, so there is currently no way to do this outside of manually doing the recall before a scene is unloaded?
I had considered making pulled objects spawn in the “DontDestroyOnLoad” scene, but the intention when unloading a scene is for all objects in that scene to be removed from play.

Expanding on Nic’s answer above, going from scene to scene implies a lot in Unity.

To gain good control of it, it’s best to make a wrapper that does it for you, and all your code would hit that wrapper.

That way other subsystems like your object pooler can subscribe to events in the wrapper to learn what’s going on. Another useful thing that might want to be notified is a music player, for example.

1 Like

This is intended to be a general purpose tool for others to use through the UPM, so I’d rather not force any workflow conventions outside of the standard. So until Unity make a callback you can subscribe to that takes place before the scene is unloaded, I’ll just add a helper method that recalls any objects in a given scene. The user will have to manually manage that, or create a wrapper as you suggested.

1 Like