SceneManager.sceneUnloaded not working

Hi all

I need to detect when a scene is unloaded in order to save player data.
However, It’s not always working as expected.

Here is my code

private void OnEnable()
{
    SceneManager.sceneUnloaded += OnLevelFinished;
}

private void OnDestroy()
{
    SceneManager.sceneUnloaded -= OnLevelFinished;
}

private void OnLevelFinished(Scene scene)
{
    print("Save player data");
}

The method OnLevelFinished is called only if I comment the method OnDestroy. The same problem occurs when I replace OnDestroy() with OnDisable(). However, it is important to unsubscribe to SceneManager.sceneUnloaded.

I’m using Unity 2017.3.0f3.

Brett

That happens because the object that is listening to the sceneUnloaded is being destroyed when the scene is unloaded. You can move the unsubscribe to the OnLevelFinished.

private void OnEnable()
{
    SceneManager.sceneUnloaded += OnLevelFinished;
}
private void OnLevelFinished(Scene scene)
{
    print("Save player data");
    SceneManager.sceneUnloaded -= OnLevelFinished;
}
2 Likes

Thank you, it’s working as expected.