从外部事件调用时,Unity SceneManager.LoadScene() 不起作用

Unity SceneManager.LoadScene() does not work when being called from external event

我在 Unity 之外编写了一个 class 库(并将其作为 DLL 放入 Unity 中),我在其中声明了一个 public 事件,我从我的统一代码中收听该事件。正在从 DLL 中调用该事件。当事件被调用时,订阅事件的方法将按我预期的方式执行,除了 UnityEngine.SceneManegement.SceneManager.LoadScene() 不是 运行ning,并且导致它之后的任何代码不运行.

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();
            }
        }
    }
}