【解决】Unity3D中无法在MQTT事件中执行Animator

问题原因:

解决方法:

解决过程

1、在 Unity 中创建一个名为 MainThreadDispatcher 的脚本,用于处理主线程操作。

cs 复制代码
using System.Collections.Generic;
using UnityEngine;

public class MainThreadDispatcher : MonoBehaviour
{
    private static MainThreadDispatcher instance;
    private static readonly Queue<System.Action> actionQueue = new Queue<System.Action>();

    private void Awake()
    {
        instance = this;
    }

    private void Update()
    {
        lock (actionQueue)
        {
            while (actionQueue.Count > 0)
            {
                System.Action action = actionQueue.Dequeue();
                action.Invoke();
            }
        }
    }

    public static void ExecuteOnMainThread(System.Action action)
    {
        lock (actionQueue)
        {
            actionQueue.Enqueue(action);
        }
    }
}

2、在 Unity 中创建一个名为 MainThreadDispatcherInitializer 的脚本,用于初始化 MainThreadDispatcher。

cs 复制代码
using UnityEngine;

public class MainThreadDispatcherInitializer : MonoBehaviour
{
    private void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
        gameObject.AddComponent<MainThreadDispatcher>();
    }
}

3、在 Unity 中创建一个名为 MainThreadDispatcherInitializer 的空 GameObject,并将 MainThreadDispatcherInitializer 脚本添加到该 GameObject 上。

4、在其他脚本中,可以通过 MainThreadDispatcher.ExecuteOnMainThread 方法将操作推送到主线程执行。

cs 复制代码
public class ExampleScript : MonoBehaviour
{
    private void Start()
    {
        // 在其他线程中执行操作
        System.Threading.Thread thread = new System.Threading.Thread(() =>
        {
            // 模拟耗时操作
            System.Threading.Thread.Sleep(2000);

            // 在主线程中执行操作
            MainThreadDispatcher.ExecuteOnMainThread(() =>
            {
                // 执行动画操作
                Debug.Log("操作在主线程中执行");
            });
        });

        thread.Start();
    }
}

在这也感谢siki学院的Sk-Sky老师耐心的帮我远程解决问题

相关推荐
SmalBox1 天前
【节点】[Adjustment-WhiteBalance节点]原理解析与实际应用
unity3d·游戏开发·图形学
SmalBox2 天前
【节点】[Adjustment-Saturation节点]原理解析与实际应用
unity3d·游戏开发·图形学
麷飞花2 天前
unity3d scene窗口选中物体, 在 hierarchy高光显示
unity·editor·unity3d·u3d·hierarchy
SmalBox3 天前
【节点】[Adjustment-ReplaceColor节点]原理解析与实际应用
unity3d·游戏开发·图形学
SmalBox4 天前
【节点】[Adjustment-InvertColors节点]原理解析与实际应用
unity3d·游戏开发·图形学
Henry_Lau6175 天前
Convai插件使用解析
ai·unity3d
SmalBox6 天前
【节点】[Adjustment-Contrast节点]原理解析与实际应用
unity3d·游戏开发·图形学
SmalBox7 天前
【节点】[Adjustment-ChannelMixer节点]原理解析与实际应用
unity3d·游戏开发·图形学
SmalBox8 天前
【节点】UnityShaderGraph节点分类介绍
unity3d·游戏开发·图形学
SmalBox9 天前
【基础】UnityShader Graph 的编辑器介绍
unity3d·游戏开发·图形学