我在Unity之外编写了一个类库(并将其作为DLL放在Unity中),在其中我声明了一个公共事件,我从unity代码中监听该事件。该事件是从DLL中调用的。当事件被调用时,订阅该事件的方法将按照我的预期执行,除了UnityEngine.SceneManegement.SceneManager.LoadScene()没有运行之外,还会导致它之后的任何代码都无法运行。
using UnityEngine.SceneManagement;
using MyDLL; // this namespace has the Client.OnConnected event
public class GameManager : MonoBehaviour
{
void Awake()
{
Client.OnConnected += () => {
Debug.Log("Connected to Server");
SceneManager.LoadScene("Main");
Debug.Log("Main Scene Loaded");
};
}
}
当Client.OnConnected事件被调用时,我可以看到"Connected to Server“被记录下来,但是场景"Main”没有被加载,"Main scene Loaded“也没有被记录下来。
有谁知道为什么会发生这种情况,以及如何解决它?
发布于 2021-11-12 06:09:32
您的问题很可能是大多数Unity API只能从Unity主线程调用。
您的OnConnected
事件似乎是异步调用的。
您需要将该呼叫分派回Unity主线程。
下面是一种常用的模式:
public class GameManager : MonoBehaviour
{
// A thread safe Queue we can append actions to that shall be executed in the next Update call
private readonly ConcurrentQueue<Action> _actions = new ConcurrentQueue<Action>();
void Awake()
{
Client.OnConnected += OnClientConnected;
}
private void OnClientConnected()
{
// Instead of immediately exciting the callback append it to the
// actions to be executed in the next Update call on the Unity main thread
_actions.Enqueue(() =>
{
Debug.Log("Connected to Server");
SceneManager.LoadScene("Main");
Debug.Log("Main Scene Loaded");
};
}
// In the main thread work of the dispatched actions
private void Update ()
{
while(_actions.Count > 0)
{
if(_actions.TryDequeue(out var action))
{
action?.Invoke();
}
}
}
}
https://stackoverflow.com/questions/69935829
复制相似问题