我正在使用websocket-sharp,它可以连接到我的websocket服务器并可以接收消息。我尝试从onMessage加载场景,但它不起作用。以下是onMessage:
ws.OnMessage += (sender, e) =>
{
Debug.Log("before load scene");
SceneManager.LoadScene("Game");
Debug.Log("after load scene");
};它可以打印before load scene,但不能加载场景,也不能打印after load scene
发布于 2019-03-10 23:13:25
尝试创建一个名为SceneListener的新类,它是一个MonoBehaviour。执行以下操作:
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;
}然后从SceneListener实例向您的回调传递一个引用:
ws.OnMessage += (sender, e) =>
{
sceneListener.Switch()
};发布于 2019-03-10 21:53:13
不幸的是,这是行不通的。WebSocketSharp回调在工作线程上运行。也许这是为了减少对渲染线程的影响(从而减少对帧速率的影响),或者这只是网络库施加的一个限制。不管怎样,Unity3d不允许我们与它的应用程序接口交互,除非是从主线程。
您可以使用Dispatcher模式来解决这个问题,See this article
https://stackoverflow.com/questions/55087912
复制相似问题