- Home /
Unity 5.4.1 OnLevelWasLoaded Workaround for Singletons?
I have some singletons in my project that used OnLevelWasLoaded functions.
I've seen some workarounds but not for Singletons that have OnLevel.... Like this One: (NOT MINE)
void OnEnable()
{
//Tell our 'OnLevelFinishedLoading' function to start listening for a scene change as soon as this script is enabled.
SceneManager.sceneLoaded += OnLevelFinishedLoading;
}
void OnDisable()
{
//Tell our 'OnLevelFinishedLoading' function to stop listening for a scene change as soon as this script is disabled. Remember to always have an unsubscription for every delegate you subscribe to!
SceneManager.sceneLoaded -= OnLevelFinishedLoading;
}
void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode)
{
Debug.Log("Level Loaded");
Debug.Log(scene.name);
Debug.Log(mode);
}
The problem is that, It's called several times, in scenes that it does not need to be called. What I need is to be able to call the "OnLevelFinishedLoading" function, only in certain scenes, not in ALL of them, that is the problem with the code shown above, it's designed for NON singleton gameobjects.
Any workaround for the Singleton gameobjects?
Thanks in advance! -Chris
Answer by paternostrox · Oct 09, 2016 at 03:19 AM
You are using an event that is triggered on every scene, so your function will be called on every scene, what you need is to write a custom event, so you can make your function listen to it instead of listening to sceneLoaded, then you can just choose which scenes to trigger the event :)
I agree with @Pedro-Paternostro. But at the same time, I wouldn't get a new event. Inside the OnLevelFinishedLoading method, you will need to throw an if condition in it. Check to see if the scene that finished was one of the scenes your are looking for. If it is a scene you were wanting this function to fire on, then put the code inside the brackets. To check, either use the scene.name or scene.buildIndex and check against an array that you provide with either the names or the build indexes of the scenes you are checking for respectively.
Answer by nrajab · Jan 10, 2017 at 04:11 AM
You can just check if the scene is the one you want:
void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode)
{
if(scene.name == "MyScene"){
//Do stuff
}
}