An Action is an event that depends on an object to exist.
The Action event should be used when we don't need something to be accessed globally, like a button being pressed, or when we need to listen from something from a specific object.
Declaring
Actions have to be declared as the first thing inside a object with the event keyword.
public class ButtonView : Actor
{
public event Action OnButtonPressed;
}
Only the object that declares the event can invoke it.
It is noted that you can use an Action to send data too:
public event Action<int> OnNumberUpdated;
public event Action<Item> OnItemUpdated;
Using an Action
Let's imagine you have a granade in your character's hand. Pretty common sight in a Low RP server. In the code, usually we would have something like:
public class Granade : Explosive
{
public event Action OnPinRemoved;
public void RemovePin()
{
// Do pin removal logic.
OnPinRemoved?.Invoke();
}
}
The OnPinRemovedevent will be used to to tell listeners that subscribed to that granade's event that the granade's pin was removed. The relevance of that OnPinRemovedevent is usually for UI related purposes, or running a local animation of a granade pin flying through your screen.
You might even think it would be easier to call it directly, and depending on your logic it might be, but we are assuming that in this case its better to keep the classes decoupled.