No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EventUnit.cs 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace Unity.VisualScripting
  5. {
  6. [SerializationVersion("A")]
  7. [SpecialUnit]
  8. public abstract class EventUnit<TArgs> : Unit, IEventUnit, IGraphElementWithData, IGraphEventHandler<TArgs>
  9. {
  10. public class Data : IGraphElementData
  11. {
  12. public EventHook hook;
  13. public Delegate handler;
  14. public bool isListening;
  15. public HashSet<Flow> activeCoroutines = new HashSet<Flow>();
  16. }
  17. public virtual IGraphElementData CreateData()
  18. {
  19. return new Data();
  20. }
  21. /// <summary>
  22. /// Run this event in a coroutine, enabling asynchronous flow like wait nodes.
  23. /// </summary>
  24. [Serialize]
  25. [Inspectable]
  26. [InspectorExpandTooltip]
  27. public bool coroutine { get; set; } = false;
  28. [DoNotSerialize]
  29. [PortLabelHidden]
  30. public ControlOutput trigger { get; private set; }
  31. [DoNotSerialize]
  32. protected abstract bool register { get; }
  33. protected override void Definition()
  34. {
  35. isControlRoot = true;
  36. trigger = ControlOutput(nameof(trigger));
  37. }
  38. public virtual EventHook GetHook(GraphReference reference)
  39. {
  40. throw new InvalidImplementationException($"Missing event hook for '{this}'.");
  41. }
  42. public virtual void StartListening(GraphStack stack)
  43. {
  44. var data = stack.GetElementData<Data>(this);
  45. if (data.isListening)
  46. {
  47. return;
  48. }
  49. if (register)
  50. {
  51. var reference = stack.ToReference();
  52. var hook = GetHook(reference);
  53. Action<TArgs> handler = args => Trigger(reference, args);
  54. EventBus.Register(hook, handler);
  55. data.hook = hook;
  56. data.handler = handler;
  57. }
  58. data.isListening = true;
  59. }
  60. public virtual void StopListening(GraphStack stack)
  61. {
  62. var data = stack.GetElementData<Data>(this);
  63. if (!data.isListening)
  64. {
  65. return;
  66. }
  67. // The coroutine's flow will dispose at the next frame, letting us
  68. // keep the current flow for clean up operations if needed
  69. foreach (var activeCoroutine in data.activeCoroutines)
  70. {
  71. activeCoroutine.StopCoroutine(false);
  72. }
  73. if (register)
  74. {
  75. EventBus.Unregister(data.hook, data.handler);
  76. stack.ClearReference();
  77. data.handler = null;
  78. }
  79. data.isListening = false;
  80. }
  81. public override void Uninstantiate(GraphReference instance)
  82. {
  83. // Here, we're relying on the fact that OnDestroy calls Uninstantiate.
  84. // We need to force-dispose any remaining coroutine to avoid
  85. // memory leaks, because OnDestroy on the runner will not keep
  86. // executing MoveNext() until our soft-destroy call at the end of Flow.Coroutine
  87. // or even dispose the coroutine's enumerator (!).
  88. var data = instance.GetElementData<Data>(this);
  89. var coroutines = data.activeCoroutines.ToHashSetPooled();
  90. #if UNITY_EDITOR
  91. new FrameDelayedCallback(() => StopAllCoroutines(coroutines), 1);
  92. #else
  93. StopAllCoroutines(coroutines);
  94. #endif
  95. base.Uninstantiate(instance);
  96. }
  97. static void StopAllCoroutines(HashSet<Flow> activeCoroutines)
  98. {
  99. // The coroutine's flow will dispose instantly, thus modifying
  100. // the activeCoroutines registry while we enumerate over it
  101. foreach (var activeCoroutine in activeCoroutines)
  102. {
  103. activeCoroutine.StopCoroutineImmediate();
  104. }
  105. activeCoroutines.Free();
  106. }
  107. public bool IsListening(GraphPointer pointer)
  108. {
  109. if (!pointer.hasData)
  110. {
  111. return false;
  112. }
  113. return pointer.GetElementData<Data>(this).isListening;
  114. }
  115. public void Trigger(GraphReference reference, TArgs args)
  116. {
  117. InternalTrigger(reference, args);
  118. }
  119. private protected virtual void InternalTrigger(GraphReference reference, TArgs args)
  120. {
  121. var flow = Flow.New(reference);
  122. if (!ShouldTrigger(flow, args))
  123. {
  124. flow.Dispose();
  125. return;
  126. }
  127. AssignArguments(flow, args);
  128. Run(flow);
  129. }
  130. protected virtual bool ShouldTrigger(Flow flow, TArgs args)
  131. {
  132. return true;
  133. }
  134. protected virtual void AssignArguments(Flow flow, TArgs args)
  135. {
  136. }
  137. private void Run(Flow flow)
  138. {
  139. if (flow.enableDebug)
  140. {
  141. var editorData = flow.stack.GetElementDebugData<IUnitDebugData>(this);
  142. editorData.lastInvokeFrame = EditorTimeBinding.frame;
  143. editorData.lastInvokeTime = EditorTimeBinding.time;
  144. }
  145. if (coroutine)
  146. {
  147. flow.StartCoroutine(trigger, flow.stack.GetElementData<Data>(this).activeCoroutines);
  148. }
  149. else
  150. {
  151. flow.Run(trigger);
  152. }
  153. }
  154. protected static bool CompareNames(Flow flow, ValueInput namePort, string calledName)
  155. {
  156. Ensure.That(nameof(calledName)).IsNotNull(calledName);
  157. return calledName.Trim().Equals(flow.GetValue<string>(namePort)?.Trim(), StringComparison.OrdinalIgnoreCase);
  158. }
  159. }
  160. }