UnityMainThreadDispatcher.cs 912 B

123456789101112131415161718192021222324252627282930313233343536
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. public class UnityMainThreadDispatcher : MonoBehaviour
  4. {
  5. private static readonly Queue<System.Action> _executionQueue = new Queue<System.Action>();
  6. private static UnityMainThreadDispatcher _instance;
  7. public static UnityMainThreadDispatcher Instance()
  8. {
  9. if (_instance == null)
  10. {
  11. GameObject go = new GameObject("MainThreadDispatcher");
  12. _instance = go.AddComponent<UnityMainThreadDispatcher>();
  13. DontDestroyOnLoad(go);
  14. }
  15. return _instance;
  16. }
  17. public void Enqueue(System.Action action)
  18. {
  19. lock (_executionQueue)
  20. {
  21. _executionQueue.Enqueue(action);
  22. }
  23. }
  24. private void Update()
  25. {
  26. while (_executionQueue.Count > 0)
  27. {
  28. var action = _executionQueue.Dequeue();
  29. action();
  30. }
  31. }
  32. }