1
\$\begingroup\$

Unity3d: I know exist OnApplicationQuit called before the application is ended.

But, does exists an event that is called before a new scene is loaded ?

Thanks

\$\endgroup\$
3
\$\begingroup\$

Yes, there is, it's SceneManager.activeSceneChanged, it's defined as follows:

public static event UnityAction<Scene, Scene> activeSceneChanged;

The first argument is the current scene, the second argument is the new scene.

There's a page in the documentation with an actual usage example:

https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-activeSceneChanged.html

\$\endgroup\$
1
\$\begingroup\$

You are likely looking for SceneManager.sceneUnloaded to get a notification when a scene has unloaded (or SceneManager.sceneLoaded to get a notification when a scene has loaded). See Unity's documentation on SceneManager.

Note that OnLevelWasLoaded is deprecated (marked as Obsolete) as of Unity 5.4. @Chris' answer is still supported, but it's preferable to use SceneManager. As that answer points out, keep in mind the Execution Order of Event Functions.

See the example code in SceneManager.sceneUnloaded documentation:

using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneLoaded1 : MonoBehaviour
{
    public void Start()
    {
        SceneManager.sceneUnloaded += OnSceneUnloaded;
        Debug.Log("Start: SceneLoaded1");
    }

    private void OnSceneUnloaded(Scene current)
    {
        Debug.Log("OnSceneUnloaded: " + current);
    }

    void Update()
    {
        if (Input.GetKey("space"))
        {
            Debug.Log("Quitting Scene1");
            ChangeScene();
        }
    }

    void ChangeScene()
    {
        Debug.Log("Changing to Scene2");

        SceneManager.LoadScene("Scene2");
    }

    void OnDestroy()
    {
        Debug.Log("OnDestroy");
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Interesting, didn't realize OnLevelWasLoaded had been deprecated. Good to know! \$\endgroup\$ – Chris Mills-Price May 4 '18 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.