From 14e3337daaa7d222d794f18ac137a09a2ea3731b Mon Sep 17 00:00:00 2001 From: Syntriax Date: Tue, 6 Feb 2024 12:09:27 +0300 Subject: [PATCH] feat: BehaviourControllerExtensions - TryGetBehaviourInParent - GetBehaviourInParent - TryGetBehaviourInChildren - GetBehaviourInChildren --- .../BehaviourControllerExtensions.cs | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Engine.Core/Extensions/BehaviourControllerExtensions.cs diff --git a/Engine.Core/Extensions/BehaviourControllerExtensions.cs b/Engine.Core/Extensions/BehaviourControllerExtensions.cs new file mode 100644 index 0000000..01a0c5d --- /dev/null +++ b/Engine.Core/Extensions/BehaviourControllerExtensions.cs @@ -0,0 +1,47 @@ +using System.Diagnostics.CodeAnalysis; + +using Syntriax.Engine.Core.Abstract; + +namespace Syntriax.Engine.Core; + +public static class BehaviourControllerExtensions +{ + public static bool TryGetBehaviourInParent(this IBehaviourController behaviourController, [NotNullWhen(returnValue: true)] out T? behaviour) where T : class + { + behaviour = GetBehaviourInParent(behaviourController); + return behaviour is not null; + } + + public static T? GetBehaviourInParent(this IBehaviourController behaviourController) where T : class + { + IBehaviourController? controller = behaviourController; + + while (controller is not null) + { + if (behaviourController.GetBehaviour() is T behaviour) + return behaviour; + + controller = controller.GameObject.Transform.Parent?.GameObject.BehaviourController; + } + + return default; + } + + public static bool TryGetBehaviourInChildren(this IBehaviourController behaviourController, [NotNullWhen(returnValue: true)] out T? behaviour) where T : class + { + behaviour = GetBehaviourInChildren(behaviourController); + return behaviour is not null; + } + + public static T? GetBehaviourInChildren(this IBehaviourController behaviourController) where T : class + { + if (behaviourController.GetBehaviour() is T localBehaviour) + return localBehaviour; + + foreach (ITransform transform in behaviourController.GameObject.Transform) + if (GetBehaviourInChildren(transform.GameObject.BehaviourController) is T behaviour) + return behaviour; + + return default; + } +}