簡體   English   中英

從外部事件調用時,Unity SceneManager.LoadScene() 不起作用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM