【问题标题】:Unity SceneManager.LoadScene() does not work when being called from external event从外部事件调用 Unity SceneManager.LoadScene() 时不起作用
【发布时间】:2021-11-11 22:40:53
【问题描述】:

我在 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 事件时,我可以看到正在记录“已连接到服务器”,但未加载场景“主”并且未记录“已加载主场景”。

有谁知道为什么会发生这种情况以及如何解决它?

【问题讨论】:

    标签: c# unity3d dll


    【解决方案1】:

    您的问题很可能是大多数 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();
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      相关资源
      最近更新 更多