Reputation: 11
I have a function that registers an Action to a specific trigger in a game. ex:
Triggers.RegisterTriggeredEvent(Trigger.OnPlayerDamage, playerDamageHandler);
I want playerDamageHandler to be a specific type ex:
void PlayerDamageHandler(Player damaged, DamageType type);
Is there a better way of doing this then run-time type checking of the action based off a Dictionary of key-value pairs ex: [OnPlayerDamage: ActionType]? Is there a way to statically check the type of the function passed to RegisterTrigger?
This can not be done using events because resolution order of triggers depends on the input of players. The triggers are registered in events and then resolved afterward in a specific order decided by the game rules.
Upvotes: 1
Views: 70
Reputation: 1072
I think it's possible. Just create an Event<THandler>
class with one instance for each event type. The type parameter THandler
is the type of the Delegate handling the event.
// Represents a single event type, e.g. PlayerDamage, PlayerDeath, etc.
public class Event<THandler> where THandler : Delegate { }
public delegate void PlayerDamageHandler(Player player, DamageType type);
public delegate void PlayerDeathHandler(Player player, DeathReason reason);
public static class Events
{
public static Event<PlayerDamageHandler> OnPlayerDamage = new Event<PlayerDamageHandler>();
public static Event<PlayerDeathHandler> OnPlayerDeath = new Event<PlayerDeathHandler>();
}
Then add the method for registering handlers,
public void RegisterTriggeredEvent<THandler>(Event<THandler> @event, THandler handler)
where THandler : Delegate
{
...
}
which you could then use like this:
RegisterTriggeredEvent(Events.OnPlayerDamage, playerDamageHandler);
If the handler has wrong parameter types, e.g.:
RegisterTriggeredEvent(Events.OnPlayerDamage, (Player p, int foo) => { ... });
a compile-time error is produced:
Parameter 2 is declared as type 'int' but should be 'DamageType'
Maybe you could put the list of handlers and the RegisterTriggeredEvent
method directly into the Event
class.
Note: The Delegate
generic constraint was added in C# 7.3 and I'm not sure if it's supported by Unity.
Upvotes: 1