using System; using System.Collections.Generic; namespace Syntriax.Engine.Core; public class BehaviourCollectorSorted : BehaviourCollector where T : class { private readonly Event.EventHandler delegateOnPriorityChanged = null!; private IComparer? _sortBy = null; public IComparer? SortBy { get => _sortBy; set { _sortBy = value; if (value is not null) behaviours.Sort(value); } } protected override void AddBehaviour(T behaviour) { if (SortBy is null) { behaviours.Add(behaviour); return; } int insertionIndex = behaviours.BinarySearch(behaviour, SortBy); if (insertionIndex < 0) insertionIndex = ~insertionIndex; behaviours.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; behaviours.Remove(behaviour); AddBehaviour(behaviour); } public BehaviourCollectorSorted() { delegateOnPriorityChanged = OnPriorityChanged; } public BehaviourCollectorSorted(IUniverse universe, Comparison sortBy) : base(universe) { delegateOnPriorityChanged = OnPriorityChanged; SortBy = Comparer.Create(sortBy); } }