MainThreadDispatcher.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // MainThreadDispatcher.cs
  2. // 非常轻量的主线程派发器(单例 MonoBehaviour)
  3. // CMDManager 会自动 EnsureCreated()
  4. using System;
  5. using System.Collections.Concurrent;
  6. using UnityEngine;
  7. public class MainThreadDispatcher : MonoBehaviour
  8. {
  9. private static MainThreadDispatcher _instance;
  10. private static readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();
  11. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
  12. private static void InitOnLoad()
  13. {
  14. // 清理旧实例引用(域重载时)
  15. _instance = null;
  16. }
  17. public static void EnsureCreated()
  18. {
  19. if (_instance != null) return;
  20. var go = new GameObject("MainThreadDispatcher");
  21. DontDestroyOnLoad(go);
  22. _instance = go.AddComponent<MainThreadDispatcher>();
  23. }
  24. public static void Enqueue(Action action)
  25. {
  26. if (action == null) return;
  27. queue.Enqueue(action);
  28. }
  29. private void Update()
  30. {
  31. while (queue.TryDequeue(out var action))
  32. {
  33. try
  34. {
  35. action();
  36. }
  37. catch (Exception e)
  38. {
  39. Debug.LogError("[MainThreadDispatcher] action error: " + e);
  40. }
  41. }
  42. }
  43. }