Guest User

Awaiters, fixed

a guest
Jan 16th, 2023
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | Source Code | 0 0
  1. using Godot;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4.  
  5. public partial class Awaiters : Node
  6. {
  7. static Awaiters _instance;
  8. public static Awaiters Instance => _instance;
  9.  
  10. static SceneTree Tree => Instance.GetTree();
  11. public static SignalAwaiter WaitNextFrame() => Tree.ToSignal(Tree, "process_frame");
  12. public static SignalAwaiter WaitSeconds(float s) => Tree.ToSignal(Tree.CreateTimer(s), "timeout");
  13.  
  14. List<System.Action> _oneshots = new List<System.Action>();
  15. List<System.Action> _processingOneshots = new List<System.Action>();
  16.  
  17. public Awaiters() : base()
  18. {
  19. if (_instance != null)
  20. {
  21. GD.PrintErr($"Multiple instances of {typeof(Awaiters).Name} Singletons created!");
  22. return;
  23. }
  24.  
  25. _instance = this;
  26. }
  27.  
  28. public override void _Notification(long what)
  29. {
  30. base._Notification(what);
  31. if (what == NotificationWmCloseRequest)
  32. {
  33. _instance = null;
  34. }
  35. }
  36.  
  37. void _ProcessOneshots()
  38. {
  39. var temp = _processingOneshots;
  40. _processingOneshots = _oneshots;
  41. _oneshots = temp;
  42. _oneshots.Clear();
  43.  
  44. foreach (var action in _processingOneshots) action?.Invoke();
  45. }
  46.  
  47. public static void AddOneshot(System.Action oneshot)
  48. {
  49. if(Instance == null) return;
  50. Instance._oneshots.Add(oneshot);
  51. Instance.SetProcess(true);
  52. }
  53.  
  54. public static void CancelOneshot(System.Action oneshot)
  55. {
  56. if(Instance == null) return;
  57. Instance._oneshots.Remove(oneshot);
  58. }
  59.  
  60. public override void _Process(double delta)
  61. {
  62. base._Process(delta);
  63. _ProcessOneshots();
  64. SetProcess(_oneshots.Count > 0);
  65. }
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment