Interesting question earlier over on Discord.
How to find the previous scene that was loaded and have that stored.
Since OnLevelWasLoaded() has now been depracated, I needed to find an alternative using SceneManagement.
Now I know there’s many ways to skin a cat, but this is just what I came up with this morning
So I have a persistent GameManager script or the like in the game and ive just added this to it.
remember to add this namespace at the top of the script tho
using UnityEngine.SceneManagement;
I just added this to a persistent game manager script
// we can use the SceneUnloaded delegate of scenemanager to listen for scenes that have been unloaded
void OnEnable() { SceneManager.sceneUnloaded += SceneUnloadedMethod; }
void OnDisable() { SceneManager.sceneUnloaded -= SceneUnloadedMethod; }
int lastSceneIndex = -1;
// looks a bit funky but the method signature must match the scenemanager delegate signature
void SceneUnloadedMethod (Scene sceneNumber)
{
int sceneIndex = sceneNumber.buildIndex;
// only want to update last scene unloaded if were not just reloading the current scene
if(lastSceneIndex != sceneIndex)
{
lastSceneIndex = sceneIndex;
Debug.Log("unloaded scene is : " + lastSceneIndex);
}
}
public int GetLastSceneNumber()
{
return lastSceneIndex;
}
Ive just stuck in a public method there at the bottom so any external script can get a hold of that scene index if needed.
like I said, there will be a more elegant way of getting this, but this is all I could think of this morning, I found it an interesting question so thought I would share what I came up with and hope it helps someone.