Unity Package for a Scriptable Object Based Event System.
This repository contains a Unity package for a simple scriptable object based event system designed to facilitate script communication across scenes without spaghetti references or anti-patterns (like singletons).
The system works by creating Game Events, which are scriptable objects that can be invoked to pass data. When invoking the created game event, you pass a (possibly null) instance of the Game Event Context class, which can hold any object as data. To listen for game event invokation, add the Game Event Listener monobehavior to a game objects, and set the callback method which recieves the Game Event Context.
The event system can be installed through the Unity Package Manager using this repository's git URL:
https://github.com/kbvatral/SO-Event-System
- Create a Game Event scriptable object for your event
- Pass a reference of this scriptable object to the invoking class
- Add the Game Event Listener monobehavior to the receiving game object
- Set the
Game Event
parameter of this monobehavior to the desired game event scriptable object - Set the
Callback
Unity event to invoke the desired behaviors when the game event is invoked. These callback methods can optionally take aGameEventContext
parameter.
- Set the
- In the invoking class, invoke the game event scriptable object, which optional context parameters
gameEvent.Invoke()
will invoke the event with a null context. Use this appoach to pass a message without any data.gameEvent.Invoke(GameEventContext ctx)
will invoke the event with the specified context objectgameEvent.Invoke(Object data)
will create a newGameEventContext
with its data set to the specified object and then invoke the event with this created context
- In the recieving class, create a callback method to handle the game event invokation and read any relevant data
gameEventContext.GetData<T>
will return the data associated with theGameEventContext
cast to typeT
. Use this to retrieve the passed data from the invoking class.- Note: The
GetData<T>
will attempt to cast the passed data to the specified type regardless of what was passed. If the cast is unsuccessful, it will returndefault(T)
. - Note: The
GameEventContext
will not handle objects which no longer exist (e.g., garbage collected or destroyed by Unity), so take extra care to check the resulting data if using in a case where this may happen.
- 1.0.0
- Initial Public Release
This project is licensed under the GPL 3.0 License - see the LICENSE file for details
Portions of this codebase were adapted and expanded from the Game Events Unity Tutorial by Jason Weimann.