68 lines
1.7 KiB
C#
68 lines
1.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace Syntriax.Engine.Core;
|
|
|
|
public class BehaviourCollectorSorted<T> : BehaviourCollector<T> where T : class
|
|
{
|
|
private readonly Event<IBehaviour, IBehaviour.PriorityChangedArguments>.EventHandler delegateOnPriorityChanged = null!;
|
|
|
|
private IComparer<T>? _sortBy = null;
|
|
public IComparer<T>? 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<T> sortBy) : base(universe)
|
|
{
|
|
delegateOnPriorityChanged = OnPriorityChanged;
|
|
|
|
SortBy = Comparer<T>.Create(sortBy);
|
|
}
|
|
}
|