I'm currently working on a small game-engine and i'm kinda stuck on finding the right pattern to subscribe to an event fired from any instance of type X.To understand what i'm trying to achieve, here are some code snippets :
public class FireEffect : BaseEffect
{
public FireEffect(BaseAbility effectOwner)
{
this.Owner = effectOwner; // each effect belong to an ability
this.Name = "Fire";
}
//apply effect on target
public override void CalculateEffect(Unit target)
{
// set the event here (to get the target as argument for the event)
this.Event = new EventDispatcher(this.Owner, new EffectEventArgs(target));
this.Event.DispatchMyEvent(); // rise/dispatch this effect event
base.CalculateEffect(target); // do stuffs like burn ..damage etc
}
}
and Let´s say we have two Units : a "dragon" with FireBall ability (contain FireEffect) and a "Shaolin" with a passiveAbility (contain WindEffect)
public class PassiveAbility : BaseAbility
{
public PassiveAbility(Unit caster)
{
this.Name = "WindFury";
this.Caster = caster; // ability caster (owner)
this.EffectList = new List<BaseEffect>(); // effects that an ability possess
this.EffectList.Add(new WindEffect(this));
this.initListeners(); // subscribe to events (aka add listeners)
}
// apply all effects that this ability has on the selected target
public override void DoAbility(Unit target)
{
foreach (BaseEffect eff in this.EffectList)
{
eff.CalculateEffect(target);
}
}
// THE MAIN PROBLEM :
public override void initListeners(){}
//call this method if FireEffect.Event was rised
public void CallBack(object sender, EffectEventArgs e)
{
BaseAbility ab = (BaseAbility)sender;
this.DoEffect(ab.UnitCaster); // hit the unit caster back (revenge)
}
}
How to subscribe via PassiveAbility.initListeners() to an event fired from any instance of type FireEffect (an ability that use fireEffect) ???
Otherwise put : when our dragon throw an ability with a FireEffect (like fireBall) on our friend "Shaolin", he should react to it using WindEffect via PassiveAbility.
Notice please that we can have so many dragons and Shaolins in this game or simulation and any passive holder (unit) should only react to the attacker (unit) etc.
Many thanks in advance for your support and contribution.