2
\$\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\$

2 Answers 2

4
\$\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
  • 1
    \$\begingroup\$ Interesting, didn't realize OnLevelWasLoaded had been deprecated. Good to know! \$\endgroup\$ Commented May 4, 2018 at 16:07

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.