PromiseManager.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright (c) 2025 TerraByte Inc.
  2. //
  3. // A static manager that hooks into the Unity Editor's update loop to process
  4. // promises, ensuring their callbacks are executed on the main thread.
  5. using UnityEditor;
  6. using System.Collections.Generic;
  7. namespace Terra.Arbitrator.Promises
  8. {
  9. [InitializeOnLoad] // Ensures the static constructor is called when the editor loads.
  10. public static class PromiseManager
  11. {
  12. private static readonly List<ITrackablePromise> PendingPromises = new();
  13. static PromiseManager()
  14. {
  15. EditorApplication.update -= Update; // Ensure we don't get duplicate subscriptions on recompile
  16. EditorApplication.update += Update;
  17. }
  18. private static void Update()
  19. {
  20. // Lock to prevent modification while iterating, in case a callback adds another promise.
  21. lock (PendingPromises)
  22. {
  23. // Iterate backwards so we can safely remove items.
  24. for (var i = PendingPromises.Count - 1; i >= 0; i--)
  25. {
  26. // The Tick() method on the promise will return true when it's finished.
  27. // We use dynamic here to call Tick() without knowing the generic type of the promise.
  28. if (PendingPromises[i].Tick())
  29. {
  30. PendingPromises.RemoveAt(i);
  31. }
  32. }
  33. }
  34. }
  35. /// <summary>
  36. /// Registers a new promise to be ticked by the manager.
  37. /// </summary>
  38. public static void Track(ITrackablePromise promise)
  39. {
  40. lock (PendingPromises)
  41. {
  42. PendingPromises.Add(promise);
  43. }
  44. }
  45. }
  46. }