90 lines
1.6 KiB
C#
90 lines
1.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace BitStrap
|
|
{
|
|
[Serializable]
|
|
public class Modifiable<T> : IModifiable
|
|
{
|
|
[SerializeField]
|
|
private T originalValue;
|
|
|
|
[SerializeField]
|
|
private T modifiedValue;
|
|
|
|
private Dictionary<object, T> modifiers = new Dictionary<object, T>();
|
|
|
|
private Func<T, T, T> aggregateFunction;
|
|
|
|
public T OriginalValue
|
|
{
|
|
get
|
|
{
|
|
return originalValue;
|
|
}
|
|
set
|
|
{
|
|
originalValue = value;
|
|
UpdateModifiedValues();
|
|
}
|
|
}
|
|
|
|
public T ModifiedValue
|
|
{
|
|
get
|
|
{
|
|
return modifiedValue;
|
|
}
|
|
}
|
|
|
|
public Modifiable(T value, Func<T, T, T> aggregateFunction)
|
|
{
|
|
originalValue = value;
|
|
this.aggregateFunction = aggregateFunction;
|
|
modifiedValue = value;
|
|
}
|
|
|
|
public static implicit operator T(Modifiable<T> modifiable)
|
|
{
|
|
return modifiable.modifiedValue;
|
|
}
|
|
|
|
public void SetModifier(object context, T modifier)
|
|
{
|
|
modifiers[context] = modifier;
|
|
UpdateModifiedValues();
|
|
}
|
|
|
|
public void RemoveModifier(object context)
|
|
{
|
|
modifiers.Remove(context);
|
|
UpdateModifiedValues();
|
|
}
|
|
|
|
public void ClearModifiers()
|
|
{
|
|
modifiers.Clear();
|
|
modifiedValue = originalValue;
|
|
}
|
|
|
|
public override string ToString()
|
|
{
|
|
return modifiedValue.ToString();
|
|
}
|
|
|
|
public void UpdateModifiedValues()
|
|
{
|
|
modifiedValue = originalValue;
|
|
T arg = originalValue;
|
|
DictionaryExtensions.GCFreeEnumerator<object, T> enumerator = modifiers.Each().GetEnumerator();
|
|
while (enumerator.MoveNext())
|
|
{
|
|
T value = enumerator.Current.Value;
|
|
modifiedValue = aggregateFunction(arg, value);
|
|
arg = value;
|
|
}
|
|
}
|
|
}
|
|
}
|