Guest User

Awaiters, old

a guest
Jan 16th, 2023
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 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. static List<System.Action> _oneshots = new List<System.Action>();
  15. static 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. static void _ProcessOneshots()
  29. {
  30. var temp = _processingOneshots;
  31. _processingOneshots = _oneshots;
  32. _oneshots = temp;
  33. _oneshots.Clear();
  34.  
  35. foreach (var action in _processingOneshots) action?.Invoke();
  36. }
  37.  
  38. public static void AddOneshot(System.Action oneshot)
  39. {
  40. _oneshots.Add(oneshot);
  41. Instance.SetProcess(true);
  42. }
  43.  
  44. public static void CancelOneshot(System.Action oneshot){
  45. _oneshots.Remove(oneshot);
  46. }
  47.  
  48. public override void _Process(double delta)
  49. {
  50. base._Process(delta);
  51. _ProcessOneshots();
  52. SetProcess(_oneshots.Count > 0);
  53. }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment