using System.Diagnostics.CodeAnalysis; using Syntriax.Engine.Core.Abstract; namespace Syntriax.Engine.Core; public static class BehaviourControllerExtensions { public static T GetOrAddBehaviour(this IBehaviourController behaviourController, params object?[]? args) where T : class, IBehaviour => behaviourController.GetBehaviour() ?? behaviourController.AddBehaviour(args); 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; } }