Search code examples
c#unity-game-engineeventsevent-handlingsignals

Why should I use a Messaging/Signal/Event library before simply System.Action in c#?


I Started developing projects using Unity that uses C#. I found tons of people recommending using libraries like https://github.com/yankooliveira/signals or http://wiki.unity3d.com/index.php/CSharpMessenger_Extended to control events like when a player hp changes, some currency changes, or whatever changes rarely in a none constant time rate.

The concept of events or signals is really powerful, but why not simply use System.Action combined with the event keyword? what advantages provide these libs?

public class SomeClass
{
    public static event Action OnSomethingChange;

    public void TriggerOnSomethingChange()
    {
        OnSomethingChange?.Invoke();
    }

    public void SubscribeToOnSomethingChange()
    {
        OnSomethingChange += OnSomethingChangeHandler;
    }

    public void UnsubscribeToOnSomethingChange()
    {
        OnSomethingChange -= OnSomethingChangeHandler;
    }

    private void OnSomethingChangeHandler()
    {
        
    }
}

Solution

  • Short

    These libraries give you a generalization of your events and you don't need to write your own system.

    A little bit more information

    When you use only Action events with event key need to remember about params that you want to pass through events, because in this library is very simple, the only thing that needs - create own class with fields, but if use your own Actions or one Action with general params necessary to use Boxing/Unboxing or common fields.