Mastering Object Communication...

What are Events?

In short, events are an abstract way for GameObjects to communicate with one another. GameObject 'A' can call a function on GameObject 'B' without either object necessarily needing to know about one-another.

How do they work?

In order to recieve an event, a GameObject must first connect via the EventSystem either using the static 'EventConnect' function or the extension method 'Connect':

public static void EventConnect(GameObject target, string eventName, Action<EventData> func);
//Extension Method
public static void Connect(this GameObject target, string eventName, Action<EventData> func);

target: The object that is expected to recieve the event.

eventName: The name of the event that is being listened for.

func: A function that returns nothing but takes in EventData as its first parameter.

Next, the event must be sent to the listening target using either the static 'EventSend' function or the 'DispatchEvent' extension method.

public static void EventSend(GameObject target, string eventName, EventData eventData = null);
//Extension Method
public static void DispatchEvent(this GameObject target, string eventName, EventData eventData = null);

eventData: An optional paramater which is used to pass data through the event. The user should store the data in a class which inherits from 'EventData'. By default, an empty EventData class is used.

Example

Output

Hello World
5

The 'Events' Class

The 'Events' class is used to create a visual interface for strings to be used as events. Adding another public static readonly string to the class will add another event to the dropdown menu of events.

Creating a public member variable of type 'Events' in a monobehavior will make it be drawn in the inspector. The events class can be implicitly converted from (or to) a string.

public Events ListenEvent = Events.DefaultEvent;

Leads to:

There is an unchecked checkbox titled 'AsString' next to a dropdown menu of all the events.

Checking 'AsString' allows a custom string to be entered:

The 'AsString' button is checked and, instead of a dropdown menu, there is a string input box.

Download the Event System!