|
Post by britannis on Mar 29, 2016 20:57:05 GMT
I have a base class for my units called CharacterModel. In that CharacterModel is a Die() function that posts a notification the character has died.
I have two classes that inherit from CharacterModel: EnemyModel and PlayerModel.
If I know the type beforehand I can just grab it from the 'sender' argument, but what about when I don't know the type? In other words, I need to know whether the character that died was an Enemy or the Player. How would I determine the sender without knowing the type beforehand?
|
|
|
Post by Admin on Mar 30, 2016 22:08:54 GMT
There are actually a lot of ways you can determine this.
1.) You could have the concrete subclass post its own event, such as "EnemyDied" and "PlayerDied" and then you can have a handler method dedicated to the correct "type" of event sender. 2.) Some people put a sort of identifier field in the shared base class. This could as one example be an enum that would be CharacterType.Enemy or CharacterType.Player. You can cast the sender to the base class regardless of the concrete subclass (this is called polymorphism) and then feel free to reference that property without worrying about what subclass it is a type of. 3.) You can check the type of the class in the handler method such as:
if (sender is EnemyModel) { // Handle enemy logic } else if (sender is PlayerModel) { // Handle player logic }
|
|