unity-game-enginewebsocket-sharp

Load Scene when websocket receive message


I am using websocket-sharp, and it can connect to my websocket server and can receive message. I try to load scene from onMessage, but it doens't work. Following is onMessage:

    ws.OnMessage += (sender, e) =>
    {
        Debug.Log("before load scene");
        SceneManager.LoadScene("Game");
        Debug.Log("after load scene");
    };

It will print before load scene, but it can not load scene and it doesn't print after load scene


Solution

  • Try creating a new class called SceneListener which is a MonoBehaviour. Do the following:

    private bool _shouldSwitch;
    void Start() {
        _shouldSwitch = false;
        DontDestroyOnLoad(this.gameObject);
    }
    
    void Update() {
        if (_shouldSwitch) {
            _shouldSwitch = false;
            Debug.Log("before load scene");
            SceneManager.LoadScene("Game");
            Debug.Log("after load scene");
        }
    }
    
    public void Switch() {
        _shouldSwitch = true;
    }
    

    Then pass a reference from the instance of SceneListener to your callback:

    ws.OnMessage += (sender, e) =>
    {
        sceneListener.Switch()
    };