[英]Unity SceneManager.LoadScene() does not work when being called from external event
我在 Unity 之外编写了一个类库(并将它作为 DLL 放入 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 事件时,我可以看到正在记录“已连接到服务器”但未加载场景“主”并且未记录“已加载主场景”。
有谁知道为什么会发生这种情况以及如何解决它?
您的问题很可能是大多数 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();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.