For the past little while, I’ve been trying to create a flexible and abstract system that allows objects to listen to events and perform some actions depending on some conditions.
This is the code I wrote:
Code
public class AttachableTrigger<TEvent, TObject> : Trigger<TEvent> where TEvent : Event
{
public TObject Container { get; set; }
public new Func<TEvent, TObject, bool> Condition { get; set; }
public new List<Action<TEvent, TObject>> Actions { get { return _actions; } }
private readonly List<Action<TEvent, TObject>> _actions = new List<Action<TEvent, TObject>>();
public new void Run(TEvent e)
{
if (IsDisabled) return;
if (Container == null) return;
if (Condition != null && !Condition(e, Container)) return;
Execute(e);
}
public new void Execute(TEvent args)
{
foreach (var action in _actions) action(args, Container);
}
}
Usage
var t = new AttachableTrigger<StatChangedEvent, Shell>();
t.Condition = (e, s) => { return e.StatType == StatType.Health && s.GetComponentInShelled<Profile>().Stats[StatType.Health].Current <= 0;};
Action<StatChangedEvent, Shell> a = (e, s) => {DoThis(s.transform.position); DoThat(s.gameObject.name = "Hi";};
t.Actions.Add(a);
The pros of the above are that it can be added / removed / modified any time, and lets an object listens to the same event but only perform actions for the triggers’ whose conditions are met.
The con is that it’s not serializable and that I haven’t seen anything like it before or any “design patterns” of this, so I’m wondering if there is another way for me to allow objects to respond differently based on some conditions?