Home > Mobile >  unity SceneManager.sceneLoaded callBack overlay each other when sceneLoaded is finished every time?
unity SceneManager.sceneLoaded callBack overlay each other when sceneLoaded is finished every time?

Time:02-24

SceneManager.sceneLoaded  = jumpCallBack;

I put this in Start() and use

private void jumpCallBack(Scene scene, LoadSceneMode sceneType)
{
    Debug.Log("ok");
}

as callback print, also I have a button, click and load this scene again.

The first time sceneLoaded finished , it print "ok" once, and I click button to load scene again, but this time, it print "ok" twice. Also click button and load again it print 3 times. Why ? How to make this call back just run once each time the sceneLoaded is called?

CodePudding user response:

In general if you want to avoid multiple callbacks

  • First of all I would usually unsubscribe before subscribing. This is valid even though if the callback was never added yet but makes sure it is definitely there only once - for this object

     SceneManager.sceneLoaded -= jumpCallBack;
     SceneManager.sceneLoaded  = jumpCallBack;
    
  • And then I think so far you were only lucky that you are only using a static method Debug.Log but nothing else in your callback. I suspect you forgot to unsubscribe when your object is destroyed

    private void OnDestroy()
    {
        SceneManager.sceneLoaded -= jumpCallBack;
    }
    

Beyond that it is hard to say without having more details about your project. If you are using e.g. DontDestroyOnLoad then you will want to also make sure there is only one instance of this object (Singleton Pattern).

  • Related