简体   繁体   中英

How to change scene in Unity when called from listener?

So as I've been told on here, I cannot call for the scene change from the Update() function. Okay, how do I implement the scene changing logic otherwise?

So for example, inside of the Update() I'm listening for the responses & requests from my server:

private void Update() {

// A bunch of parsing stuff

switch (DataFromServer) {

   case "ServerAllowedSceneChange":

      SceneManager.LoadScene(DataFromServer[2]);
      break;

   }

}

That's how I see the implementation logic, however, that's not how Unity appears to do it. Could someone advice on how to do something similar in the way that Unity will work :)

The downside of this method, which actually kind of works, is that the scene is not ready to be worked with when I call it that way. Right after the scene change call, I try to access objects that do not exist yet. And all checks for level finished loading do not work.

So that if we go back to the code example, if I do this:

switch (DataFromServer) {

   case "ServerAllowedSceneChange":

      SceneManager.LoadScene(DataFromServer[2]);
      GameObject objectFromSceneImSwithcingTo = GameObject.Find("objectFromSceneImSwithcingTo").gameObject;
      break;

   }

I get the NullReference error from Unity.

The SceneManager API has events you can subscribe for scene changes. For example:

  using UnityEngine.SceneManagement;

  void OnEnable() 
  {
      SceneManager.sceneLoaded += OnSceneLoaded;
  }

  void OnDisable() 
  {
      SceneManager.sceneLoaded -= OnSceneLoaded;
  }

  private void OnSceneLoaded(Scene scene, LoadSceneMode mode) 
  {
      // all objects are loaded, call other methods
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM