C# Action from Event

I have large sets of events (onMouseClick, OnButtonPress, OnBoxLoad, OnEnemyDie, etc)

And a large set of actions (LoadBox, ThrustForward, BlowUp, AddHealth, etc)

The goal is to allow the user to create their own bindings by adding an action to an event.

Perhaps something like KeyPressed += new EventHandler(LoadBox), where KeyPressed is an event, and LoadBox is an Action(Action<T,T>)

I think this should work in theory, if I have a list of events and a list of actions and allow the player to pick an event and an action to add to its observers…but I can’t get the code to work.

The closest I have gotten is:

public void AttachEventToFunction(Event TheEvent,EventArgs TheArgs, Action TheFunction)
{
	TheEvent +=  new EventHandler<TheArgs>(TheFunction);
}

Which, Obviously, Does not work. How can I make this work? Is there a better way to go about what I am trying to do? Am I asking this in the wrong place?

I don’t know if this can help you, but it’s possible to implement something similar to the an event handler with Component.BroadcastMessage .

You could create an OnEnemyDie(Transform enemy) event using something like this:

Transform root;

void SendEventOnEnemyDie(Transform enemy){
  root.BroadcastMessage("OnEnemyDie", enemy, SendMessageOptions.DontRequireReceiver);
}

This will call the function OnEnemyDie(Transform enemy) in any script attached to the root object or to any of its children (DontRequireReceiver prevents runtime errors in scripts where the function doesn’t exist).

Unfortunatelly, you must have a reference to the root object - there’s no documented way to use it in all game objects at once (but I suspect that some undocumented method can do that).

A simple way to work around this is to child all objects to a common root object - if you’re allowed to do that, of course.