- Home /
SceneManager.sceneloaded runs later than OnLevelWasLoaded and Breaks C# Messenger. Any help with fixes?
I use the Advanced C# Messenger from here:
http://wiki.unity3d.com/index.php?title=Advanced_CSharp_Messenger
In the messenger helper function it uses OnLevelWasLoaded to perform a cleanup of the message table:
//This manager will ensure that the messenger's eventTable will be cleaned up upon loading of a new level.
public sealed class MessengerHelper : MonoBehaviour {
void Awake ()
{
DontDestroyOnLoad(gameObject);
}
//Clean up eventTable every time a new level loads.
public void OnLevelWasLoaded(int unused) {
Messenger.Cleanup();
}
}
I have edited this to work with the SceneManager delegate like so:
//This manager will ensure that the messenger's eventTable will be cleaned up upon loading of a new level.
public sealed class MessengerHelper : MonoBehaviour {
void Awake ()
{
DontDestroyOnLoad(gameObject);
}
private void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
//Clean up eventTable every time a new level loads.
public void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
Messenger.Cleanup();
}
}
The problem is I create listeners in OnEnable() functions, and while this worked fine with OnLevelWasLoaded, SceneManager.sceneLoaded seems to run later, and has the problem of deleting all the messenger listeners I have added in the OnEnable() functions.
Is there a call similar to the OnLevelWasLoaded that runs earlier than the sceneLoaded option?
Answer by Harinezumi · May 25, 2018 at 08:41 AM
SceneManager.sceneLoaded
callback is not a good substitution for what OnLevelWasLoaded()
was doing (and many users are annoyed by Unity removing it), because it works differently.
However, if you add messenger listeners in OnEnable()
, you could remove them in OnDisable()
, or even better, OnDestroy()
. OnDestroy()
is called when a game object is destroyed, which I'm pretty sure happens when you switch a scene.
Your answer
![](https://koobas.hobune.stream/wayback/20220612141021im_/https://answers.unity.com/themes/thub/images/avi.jpg)