当前位置: 首页> 财经> 股票 > 广州排名seo公司_分销系统搭建_利搜网站排名软件_策划公司排行榜

广州排名seo公司_分销系统搭建_利搜网站排名软件_策划公司排行榜

时间:2025/7/8 22:42:51来源:https://blog.csdn.net/weixin_53501436/article/details/145570033 浏览次数:0次
广州排名seo公司_分销系统搭建_利搜网站排名软件_策划公司排行榜
① UnityMainThreadDispatcher作为工具类,用于在非主线程中将任务调度到主线程执行
using System;
using System.Collections.Generic;
using UnityEngine;public class UnityMainThreadDispatcher : MonoBehaviour
{// 用于存储需要在主线程中执行的任务队列private static readonly Queue<Action> _executionQueue = new Queue<Action>();// 单例实例private static UnityMainThreadDispatcher _instance = null;// 获取单例实例的方法public static UnityMainThreadDispatcher Instance(){// 如果实例为空,尝试在场景中查找if (_instance == null){_instance = FindObjectOfType<UnityMainThreadDispatcher>();// 如果场景中没有找到,创建一个新的 GameObject 并附加此脚本if (_instance == null){_instance = new GameObject("UnityMainThreadDispatcher").AddComponent<UnityMainThreadDispatcher>();}}return _instance;}// 每帧调用,用于执行队列中的任务private void Update(){// 使用锁确保线程安全lock (_executionQueue){// 遍历队列并执行所有任务while (_executionQueue.Count > 0){_executionQueue.Dequeue().Invoke();}}}// 将任务添加到队列中public void Enqueue(Action action){// 使用锁确保线程安全lock (_executionQueue){_executionQueue.Enqueue(action);}}// 在场景加载前初始化单例实例[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]private static void Initialize(){// 调用 Instance() 方法以确保实例被创建Instance();}
}
  使用示例脚本:
  1. 在 Start 中创建一个新线程并启动,模拟在非主线程中执行任务。
  2. DoWork() 方法
    这是一个在非主线程中运行的方法。它模拟了一些耗时操作(如 Thread.Sleep(1000)),然后通过 UnityMainThreadDispatcher 将任务添加到主线程队列中。
using System.Threading;
using UnityEngine;public class Example : MonoBehaviour
{void Start(){// 创建一个新线程并启动Thread thread = new Thread(DoWork);thread.Start();}void DoWork(){// 模拟一些耗时操作Thread.Sleep(1000);// 将任务添加到主线程队列中UnityMainThreadDispatcher.Instance().Enqueue(() =>{Debug.Log("This is executed on the main thread.");Debug.Log("GameObject active state: " + gameObject.activeSelf);});}
}

感谢大家的观看,您的点赞和关注是我最大的动力

不定时更新知识点和干货呦~

关键字:广州排名seo公司_分销系统搭建_利搜网站排名软件_策划公司排行榜

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: