首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从外部事件调用Unity SceneManager.LoadScene()时不起作用

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

Stack Overflow用户
提问于 2021-11-11 22:40:53
回答 1查看 72关注 0票数 1

我在Unity之外编写了一个类库(并将其作为DLL放在Unity中),在其中我声明了一个公共事件,我从unity代码中监听该事件。该事件是从DLL中调用的。当事件被调用时,订阅该事件的方法将按照我的预期执行,除了UnityEngine.SceneManegement.SceneManager.LoadScene()没有运行之外,还会导致它之后的任何代码都无法运行。

代码语言:javascript
运行
复制
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“也没有被记录下来。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-12 06:09:32

您的问题很可能是大多数Unity API只能从Unity主线程调用。

您的OnConnected事件似乎是异步调用的。

您需要将该呼叫分派回Unity主线程。

下面是一种常用的模式:

代码语言:javascript
运行
复制
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();
            }
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69935829

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档