Simple Action Hooks

If you need to add a simple hook that can be subscribed to and then called when something specific happens, you can do it with System.Action.

For example, I needed a few objects to be notified when the player would enable or disable certain features using a toggle checkbox.  In the class managing the UI I added the following line:

    public static System.Action OnEnabledChanged;

When the toggle was changed by the player, the following code is executed:

            if (OnEnabledChanged!=null)
                OnEnabledChanged();

In each of the other objects that needed to be notified of this event, I then added the following line:

        UIManager.OnEnabledChanged += onEnabledChanged;

where onEnabledChanged is a local function that is called when the UIManager responds to the player tapping on the checkbox.  The event can be subscribed to by multiple objects, though the only caveat is to make sure if a subscribed object is destroyed it unsubscribes from the event by using:

        UIManager.OnEnabledChanged -= onEnabledChanged;

Or you’ll start getting errors.

If you need to pass a parameter to your subscribed events, then you can do so with a simple modification:

    public static System.Action<bool> OnEnabledChanged;

and

            if (OnEnabledChanged!=null)
                OnEnabledChanged(isEnabled);

Your subscribed functions will now need to accepted a bool parameter (for example).

Leave a Reply