I'd like to send, receive and cast a subclass of a SkillEvent class and be able to grab custom parameters inside, depending of it's type.
There could be a lot of different subclasses with different parameters.
Is there a way to avoid writing a different method for each kind of skill ?
class SkillEvent { float timestamp, EventType type }
class GrenadeSkillEvent : SkillEvent { Vector3 target_point}
[ClientRpc]
RpcSendSkillEvent(SkillEvent event){
eventManager.ExecuteEvent(event);
}
ExecuteEvent(SkillEvent event){
switch(event.type){
case GrenadeSkillEvent :
GrenadeSkillEvent grenadeEvent = (GrenadeSkillEvent) event;
float grenadeParam = event.grenadeParam;
break;
case OtherSkillEvent :
OtherSkillEvent otherEvent = (OtherSkillEvent ) event;
string stringParam = event.stringParam;
break;
}
}
I thought it could be done like that, but apparently not.
Is there a way to avoid writing a different method for each kind of skill ?
Edit :
GrenadeSkillEvent and OtherSkillEvent are child of SkillEvent.
They all have a timestamp and a type that I thought I could need to help casting the event variable into the right SkillEvent subclass.
My problem is that they have the same method, let say execute, but every kind of subclass needs a different type of parameter.
For example, a GrenadeEvent could need a target point, the size of the blast and the damages.
A BonusEvent could add some HP to a player.
A TerrainEvent could activate some custom animation on an important object close to the player, etc.
All the logic behind these skill is the same.
They all have 2 methods :
Simulate(SkillEvent Event) and Render(SkillEvent Event)
But in GrenadeSkill for example I need it to be
Simulate(GrenadeSkillEvent Event) and Render(GrenadeSkillEvent Event)
Edit 2 :
networkedPlayer.RpcOnSkillEvent(
new SkillEvent[] {
new GrenadeSkillEvent() {
timestamp = state.timestamp,
id = 0,
point = target
}
}
);
Edit 3:
var dictionary = new Dictionary<Type, Action<SkillEvent>> {
{
typeof(GrenadeSkillEvent), (SkillEvent e) => {
Debug.Log("GrenadeSkill OnConfirm point"+ ((GrenadeSkillEvent)e).point);
}
}
};
public override void OnConfirm(SkillEvent skillEvent) {
if (skillEvent == null) return;
Debug.Log(skillEvent.GetType());
dictionary[skillEvent.GetType()](skillEvent);
}