0

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

Thomas
  • 1,805
  • 1
  • 15
  • 31

2 Answers2

1

Unfortunately, this won’t work. The WebSocketSharp call backs runs on a worker-thread. Maybe this is to reduce the impact on the rendering-thread (and thus on our framerate) or maybe it just a limitation imposed by the networking library. Whichever, Unity3d will not allow us to interact with its API except from the main thread.

You can use Dispatcher Pattern to solve this issue, See this article

user1579019
  • 455
  • 1
  • 7
  • 19
1

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()
};
Tomer Shahar
  • 343
  • 1
  • 8