Events

The events system is a simple extension to system actions that makes sure no method is over-subscribed to.

Scarlet.Runtime

Scarlet.EventsSystem

Usage

Event Creation

To get started with the events system you’ll need to first create an event. This can either be in the Events.cs class provided in this library or in any static class of your own. It’s recommended to use a static class for ease of access to the events. To define an event, write something like the examples below:

public static readonly Evt GameOver = new Evt();

Making the events readonly just helps us not edit it accidentally and defining it as a new event is just cleaner as it won’t need to be initialized anywhere else before use.

For events with parameters there are 8 extra classes in the Evt.cs file that allow for it. If you need more parameters, you can make additional ones as they all follow the same setup, just with an extra generic field to use in the class. To define a parameter event, use something like the following:

public static readonly Evt<int> MoneyCollected = new Evt<int>();

Event Subscribing

Subscribing to events is as easy as it is to do with actions. Instead of using += or -= to subscribe, the events system has 2 simple methods, being Add() & Remove(). Note that any method subscribing to an event will need to have the same number of parameters of the same type to subscribe correctly. Some examples using the same events defined in the creation section above:

private void OnEnable()
{
    GameOver.Add(MyVoidMethod);
}

private void OnDisable()
{
    GameOver.Remove(MyVoidMethod);
}

private void MyVoidMethod()
{
    // Some code here...
}
private void OnEnable()
{
    MoneyCollected.Add(MyIntMethod);
}

private void OnDisable()
{
   MoneyCollected.Remove(MyIntMethod);
}

private void MyIntMethod(int value)
{
    // Some code here...
}

Event Raising

Raising events is essentially invoking the action. It is done by just calling the Raise() method on the event you want to call. Using the examples from above again to showcase this:

private void OnSomeGameStateChanged()
{
    GameOver.Raise();
    MoneyCollected.Raise(money);
}

Delayed Events

You can use delayed events from the DelayedEvt.cs class. It works exactly the same as the standard Evt.cs class with the exception of the raise method having an extra option parameter for the delay. The delay is defined in milliseconds, so 1000 = 1 second & 500 = 0.5 etc.

private DelatedEvt DelayedExample = new DelayedEvt();
private DelayedEvt<string> DelayedEvtParam = new DelayedEvt<string>();

private void OnEnable()
{
    DelatedEvt.Raise(1000);
    DelayedEvtParam.Raise("Hello", 500);
}