using System; using System.Collections.Generic; namespace Syntriax.Engine.Core; public class ActiveBehaviourCollectorSorted : ActiveBehaviourCollector where T : class, IBehaviour { private readonly Event.EventHandler delegateOnPriorityChanged = null!; private IComparer? _sortBy = null; public IComparer? SortBy { get => _sortBy; set { _sortBy = value; if (value is not null) activeBehaviours.Sort(value); } } protected override void AddBehaviour(T behaviour) { if (SortBy is null) { activeBehaviours.Add(behaviour); return; } int insertionIndex = activeBehaviours.BinarySearch(behaviour, SortBy); if (insertionIndex < 0) insertionIndex = ~insertionIndex; activeBehaviours.Insert(insertionIndex, behaviour); } protected override void OnBehaviourAdd(IBehaviour behaviour) { behaviour.OnPriorityChanged.AddListener(delegateOnPriorityChanged); } protected override void OnBehaviourRemove(IBehaviour behaviour) { behaviour.OnPriorityChanged.RemoveListener(delegateOnPriorityChanged); } private void OnPriorityChanged(IBehaviour sender, IBehaviour.PriorityChangedArguments args) { T behaviour = (T)sender; activeBehaviours.Remove(behaviour); AddBehaviour(behaviour); } public ActiveBehaviourCollectorSorted() { delegateOnPriorityChanged = OnPriorityChanged; } public ActiveBehaviourCollectorSorted(IUniverse universe, Comparison sortBy) : base(universe) { delegateOnPriorityChanged = OnPriorityChanged; SortBy = Comparer.Create(sortBy); } }