feat: IBehaviourController.GetBehaviour

This commit is contained in:
Syntriax 2024-01-31 18:32:53 +03:00
parent de336d0ee5
commit 6c36d4d21d
2 changed files with 18 additions and 9 deletions

View File

@ -51,6 +51,15 @@ public interface IBehaviourController : IAssignableGameObject, IEnumerable<IBeha
/// <returns>The instantiated <see cref="IBehaviour"/> class after initialization.</returns> /// <returns>The instantiated <see cref="IBehaviour"/> class after initialization.</returns>
T AddBehaviour<T>(params object?[]? args) where T : class, IBehaviour; T AddBehaviour<T>(params object?[]? args) where T : class, IBehaviour;
/// <summary>
/// Looks up and returns the <see cref="IBehaviour"/> that is controlled by the <see cref="IBehaviourController"/>.
/// </summary>
/// <typeparam name="T">An implemented class or <see cref="interface"/></typeparam>
/// <returns>
/// <see cref="T"/>, if the type of <see cref="IBehaviour"/> is present in the <see cref="IBehaviourController"/>, <see cref="null"/> if not.
/// </returns>
T? GetBehaviour<T>();
/// <summary> /// <summary>
/// Looks up and tries to get the <see cref="IBehaviour"/> that is controlled by the <see cref="IBehaviourController"/>. /// Looks up and tries to get the <see cref="IBehaviour"/> that is controlled by the <see cref="IBehaviourController"/>.
/// </summary> /// </summary>

View File

@ -41,19 +41,19 @@ public class BehaviourController : IBehaviourController
public T AddBehaviour<T>(params object?[]? args) where T : class, IBehaviour public T AddBehaviour<T>(params object?[]? args) where T : class, IBehaviour
=> AddBehaviour(new Factory.BehaviourFactory().Instantiate<T>(_gameObject, args)); => AddBehaviour(new Factory.BehaviourFactory().Instantiate<T>(_gameObject, args));
public bool TryGetBehaviour<T>([NotNullWhen(returnValue: true)] out T? behaviour) public T? GetBehaviour<T>()
{ {
foreach (var behaviourItem in behaviours) foreach (var behaviourItem in behaviours)
{ if (behaviourItem is T result)
if (behaviourItem is not T result) return result;
continue;
behaviour = result; return default;
return true; }
}
behaviour = default; public bool TryGetBehaviour<T>([NotNullWhen(returnValue: true)] out T? behaviour)
return false; {
behaviour = GetBehaviour<T>();
return behaviour is not null;
} }
public IList<T> GetBehaviours<T>() public IList<T> GetBehaviours<T>()