Events

The event add-on is included by default in the Databrain package

The Event add-on is an object-based generic event system. It supports class types as parameters.

Register Listener

Register a listener to the event.

databrainEvent.RegisterListener(Action<T> _data);

UnregisterListener

remove listener from event

databrainEvent.UnregisterListener(Action<T> _data);

Raise Event

Raise an event.

databrainEvent.Raise(T);

Custom event object

Here's an example of a custom event object, including a parameter class

public class MyEvent : DatabrainGenericEvent<MyEventData>{}

// Event parameter class
public class MyEventData
{
    public float param1;
    public string param2;
    
    // Constructor
    public MyEventData(){}
}

You can now use this event like this:

EventCaller.cs

// Event caller example
public class EventCaller : MonoBehaviour
{
    public DataLibrary data;
    
    [DataObjectDropdown("data")]
    public MyEvent myEvent;
    
    // Using IMGUI for testing purposes only
    public void OnGUI()
    {
        if (GUILayout.Button("Call Event"))
        {
            // Create parameters
            var _params = new MyEventData();
            _params.param1 = 99.9f;
            _params.param2 = "My Event";
            // Raise event
            myEvent.Raise(_params);
        }
    }
}

EventListener.cs

public class EventListener : MonoBehaviour
{
    public DataLibrary data;
    
    [DataObjectDropdown("data")]
    public MyEvent myEvent;
    
    public void Start()
    {
        // As with all DataObjects we have to make sure the DataLibrary is ready
        // before using it.
        data.RegisterInitializationCallback(Ready);
    }
    
    void Ready()
    {
        // DataLibrary is ready. We can now register to the event
        myEvent.RegisterListener(EventCalled);
    }
    
    void EventCalled(MyEventData _data)
    {
        // Event has been called
        Debug.Log("EVENT CALLED " + _data.param1 + " _ " + _data.param2);
    }
}

Global DatabrainEvent

You can also use the base type - DatabrainEvent for global events which do not require any parameters.

public DatabrainEvent myEvent;

myEvent.Raise();

Last updated