【解决】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老师耐心的帮我远程解决问题

相关推荐
留待舞人归19 天前
【Unity3D优化】优化多语言字体包大小
游戏·unity·游戏引擎·unity3d·优化
留待舞人归22 天前
【Unity优化】提高热更新和打包速度
游戏·unity·游戏引擎·unity3d·优化
Thomas游戏开发24 天前
Unity3D 自动化游戏框架设计
前端框架·unity3d·游戏开发
一名用户1 个月前
unity实现自定义粒子系统
c#·unity3d·游戏开发
Thomas游戏开发1 个月前
Unity3D TextMeshPro终极使用指南
前端·unity3d·游戏开发
Thomas游戏开发1 个月前
Unity3D 逻辑代码性能优化策略
前端框架·unity3d·游戏开发
Thomas游戏开发1 个月前
Unity3D HUD高性能优化方案
前端框架·unity3d·游戏开发
一名用户1 个月前
unity随机生成未知符号教程
c#·unity3d·游戏开发
Thomas_YXQ1 个月前
Unity3D HUD UI性能优化方案
开发语言·ui·搜索引擎·性能优化·全文检索·unity3d
Thomas_YXQ2 个月前
Unity3D Overdraw性能优化详解
开发语言·人工智能·性能优化·unity3d