| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- // MainThreadDispatcher.cs
- // 非常轻量的主线程派发器(单例 MonoBehaviour)
- // CMDManager 会自动 EnsureCreated()
- using System;
- using System.Collections.Concurrent;
- using UnityEngine;
- public class MainThreadDispatcher : MonoBehaviour
- {
- private static MainThreadDispatcher _instance;
- private static readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();
- [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
- private static void InitOnLoad()
- {
- // 清理旧实例引用(域重载时)
- _instance = null;
- }
- public static void EnsureCreated()
- {
- if (_instance != null) return;
- var go = new GameObject("MainThreadDispatcher");
- DontDestroyOnLoad(go);
- _instance = go.AddComponent<MainThreadDispatcher>();
- }
- public static void Enqueue(Action action)
- {
- if (action == null) return;
- queue.Enqueue(action);
- }
- private void Update()
- {
- while (queue.TryDequeue(out var action))
- {
- try
- {
- action();
- }
- catch (Exception e)
- {
- Debug.LogError("[MainThreadDispatcher] action error: " + e);
- }
- }
- }
- }
|