diff --git a/Engine.Core/Extensions/BehaviourControllerExtensions.cs b/Engine.Core/Extensions/BehaviourControllerExtensions.cs index 3e82630..6778065 100644 --- a/Engine.Core/Extensions/BehaviourControllerExtensions.cs +++ b/Engine.Core/Extensions/BehaviourControllerExtensions.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Syntriax.Engine.Core.Exceptions; @@ -81,6 +82,27 @@ public static class BehaviourControllerExtensions public static T GetRequiredBehaviourInParent(this IBehaviourController behaviourController) where T : class => behaviourController.GetBehaviourInParent() ?? throw new BehaviourNotFoundException($"{behaviourController.UniverseObject.Name}'s {nameof(IBehaviourController)} does not contain any {typeof(T).FullName} on any parent"); + /// + /// Gets all s of the specified type in it's 's parents recursively and stores them in the provided list. + /// + /// The type of s to get. + /// The list to store the s. + public static void GetBehavioursInParent(this IBehaviourController behaviourController, IList behavioursInParent) where T : class + { + IBehaviourController? controller = behaviourController; + List cache = []; + behavioursInParent.Clear(); + + while (controller is not null) + { + controller.GetBehaviours(cache); + foreach (T behaviour in cache) + behavioursInParent.Add(behaviour); + + controller = controller.UniverseObject.Parent?.BehaviourController; + } + } + /// /// Tries to get a of the specified type in it's 's children recursively. /// @@ -120,4 +142,28 @@ public static class BehaviourControllerExtensions /// The of the specified type if found; otherwise, throws . public static T GetRequiredBehaviourInChildren(this IBehaviourController behaviourController) where T : class => behaviourController.GetBehaviourInChildren() ?? throw new BehaviourNotFoundException($"{behaviourController.UniverseObject.Name}'s {nameof(IBehaviourController)} does not contain any {typeof(T).FullName} on any children "); + + /// + /// Gets all s of the specified type in it's 's children recursively and stores them in the provided list. + /// + /// The type of s to get. + /// The list to store the s. + public static void GetBehavioursInChildren(this IBehaviourController behaviourController, IList behavioursInChildren) where T : class + { + List cache = []; + behavioursInChildren.Clear(); + + TraverseChildrenForBehaviour(behaviourController.UniverseObject, behavioursInChildren, cache); + } + + private static void TraverseChildrenForBehaviour(IUniverseObject universeObject, IList behaviours, IList cache) where T : class + { + universeObject.BehaviourController.GetBehaviours(cache); + + foreach (T behaviour in cache) + behaviours.Add(behaviour); + + foreach (IUniverseObject child in universeObject) + TraverseChildrenForBehaviour(child, behaviours, cache); + } }