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

相关推荐
鑫鑫哥adam2 天前
一个 1x1 贴图,是怎么炸掉整个热更包的?
unity3d·游戏开发
Behavior2 天前
Unity 手游动态更换 App 图标 — Android 与 iOS 双端技术方案
c#·unity3d·游戏开发
SmalBox3 天前
03-03-架构篇-Runtime加载系统架构
unity3d·游戏开发
SmalBox3 天前
03-02-架构篇-Editor打包系统架构
unity3d·游戏开发
Behavior3 天前
Unity 手游 iOS Deep Link 唤醒全流程:从 URL Scheme / Universal Links 到 C# 层参数投递
c#·unity3d·游戏开发
SmalBox3 天前
03-01-架构篇-整体架构总览
unity3d·游戏开发
SmalBox3 天前
02-08-原理篇-异步加载与性能优化
unity3d·游戏开发
字节暗面3 天前
Unity AssetBundle 热更新安全排查:从 CDN 清单到本地缓存
unity3d·图片资源
SmalBox8 天前
02-07-原理篇-文件系统与跨平台适配
unity3d·游戏开发
SmalBox10 天前
02-06-原理篇-热更新与版本管理
unity3d·游戏开发