Hi there I was wondering the best way to call a function when the scene exits? This code works only when the application is terminated or stopped via the unity editor.
public void OnApplicationQuit()
{
Save();
}
Trying to get that to work when the scene is changed with
[
Application.LoadLevel("TitleScreen");
was looking for something like scene exit or something but does not seem to exist. Please advise thank you.
Unless you are using coroutines you can call the function BEFORE Application.LoadLevel. You can also use DoNotDestroyOnLoad if you are using a coroutine
so this is how it youls look like if you want to save before loading a scene…
if(YourCondition)
{
Save();
Application.LoadLevel( “TitleScreen”);
}
For anyone else that finds this thread… OnDestroy() can be used to call your Save function before scene change.
OnDestroy occurs when a Scene or game ends. Stopping the Play mode when running from inside the Editor will end the application. As this end happens an OnDestroy will be executed. Also, if a Scene is closed and a new Scene is loaded the OnDestroy call will be made.
When built as a standalone application OnDestroy calls are made when Scenes end. A Scene ending typically means a new Scene is loaded.
Note: OnDestroy will only be called on game objects that have previously been active.
But OnDestroy does not solve the question at hand.
The reason we have OnApplicationQuit, is to help us differentiate between the various types of disablement and destruction.
OnDestroy is Called When an object is Destroyed, When the Scene is Destroyed and When the Application Quits.
So to be able to say, OnActiveSceneQuit allows the differentiation between a scene ending, and a standard destruction of an object.
eg. Lets say you want to instantiate an object when an another object dies, repleting the cycle of life without using an update loop to maintain said cycle.
You need to ensure a scene is not being destroyed, AND ensure the application is not quitting.
Otherwise you will have objects that get instantiated post scene destruction and it becomes a mess from there.