UnityMainThreadDispatcher.cs 989 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. public class UnityMainThreadDispatcher : MonoBehaviour
  4. {
  5. private static UnityMainThreadDispatcher _instance;
  6. private static readonly Queue<System.Action> _executionQueue = new Queue<System.Action>();
  7. // 确保在Awake中初始化实例
  8. void Awake()
  9. {
  10. if (_instance == null)
  11. {
  12. _instance = this;
  13. DontDestroyOnLoad(gameObject);
  14. }
  15. else
  16. {
  17. Destroy(gameObject);
  18. }
  19. }
  20. public static UnityMainThreadDispatcher Instance()
  21. {
  22. if (_instance == null)
  23. {
  24. Debug.LogError("UnityMainThreadDispatcher not found in scene. Please add it to a GameObject.");
  25. }
  26. return _instance;
  27. }
  28. public void Enqueue(System.Action action)
  29. {
  30. lock (_executionQueue)
  31. {
  32. _executionQueue.Enqueue(action);
  33. }
  34. }
  35. void Update()
  36. {
  37. lock (_executionQueue)
  38. {
  39. while (_executionQueue.Count > 0)
  40. {
  41. _executionQueue.Dequeue().Invoke();
  42. }
  43. }
  44. }
  45. }