Events

Events are ScriptableObjects which contain one event, either with one or no argument. You can think of them as channels that any object, from any scene, can tap into.

Additionally, they present a button in their Inspector that allows to fire the event on demand, for testing purposes.

Sample usage 💡

In an action game, a player character Prefab could broadcast its death on a "OnPlayerDied" SO Event. Any object in the game that needs to react to it, all the way up to a game manager, can reference into that SO to react.


Using Events

Creating a new Event

To create a new Event, simply position your mouse in the Project View and right click, then Create > ScriptableObject Tools > Events, and then choose the type you want to create.

Referencing an Event in scripts

Like usual, expose a public or serialised property of the right type:

public VoidEvent playerDiedEvent;
// Or also
[SerializeField] private VoidEvent _playerDiedEvent;

Listening to an event

The event contained in the ScriptableObject is not public, so to hook an object to an event, you can use the syntax as if the SO was the event itself.

Firing an event

To fire on a SO Event, use the Invoke() method, passing the correct arguments:


Extending Events

Extending the Event system with a new class is simple. To create a new event that carries one, two or three arguments, all you need to do is to create a new C# file and subclass one of the existing implementations.

For instance, inheriting from EventOneArg<T> like this (we'll use Collider as an example):

In cases like these, nothing else is needed. The event SO will also display the Invoke button automatically.

If your event's arguments are of type Struct, don't forget to add the [Serializable] attribute to your Struct.

New event with four or more arguments

It's also possible to add an event with four or more arguments, but this guide doesn't cover it. You can use EventThreeArg<T> as a guide. You might also want to write a custom Inspector for it, using for instance EventThreeArgsEditor as a reference.

Last updated