- Home /
OnSceneExit?
Hello, how can I do something when the player leaves the scene? Just like the OnApplicationQuit :-)
Thanks, Andreas.
Well you could either do it at the start of the next scene or just delay the change of scene and do something at that time. Could we ask what you want to do exactly?
I would like to save my PlayerPrefs, when the scene changes :-)
What I would usually do is create a function OnExit. and before the level finishes for whatever reason you call the function OnExit and you save everything there and then load the next scene :)
Answer by Kerihobo · Jun 29, 2017 at 06:19 AM
There is OnDestroy() which might work, because all objects are destroyed when you leave a scene.
Answer by Velocity42 · Oct 27, 2017 at 04:30 PM
You can write a function with the same signature as UnityAction, and add it to the sceneUnloaded event. Here's an example:
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
public class MyClass : MonoBehaviour {
void Awake () {
SceneManager.sceneUnloaded += MyFunction;
}
void MyFunction<Scene> (Scene scene) {
print ("The scene was unloaded!");
}
}
You can add several functions to the sceneUnloaded event, and they will all be executed when the scene is unloaded.
Answer by LucasKlein16 · May 02, 2017 at 08:13 AM
I wish this existed but it does not.
Sure it does - you add a delegate to the sceneUnloaded event.