GameEvents is a ScriptableObject driven event system for decoupling Monobehaviour components in Unity. This system was largely inspired by the following Unite presentations:
Richard Fine - Overthrowing the MonoBehaviour Tyranny in a Glorious Scriptable Object Revolution
Ryan Hipple - Game Architecture with Scriptable Objects
Each event is represented by a GameEventAsset object that is saved in the project assets, which can then be referenced in your own code or through the included GameEventCaller and GameEventListener components.
A custom editor is included that automates the creation of new GameEvent Asset/Caller/Listener classes.
Unity 2020.1 or later, GameEvents uses the Serializable Generics functionality added in 2020.1 and will absolutely not function in any version before.
Warning
Requires Odin Inspector for custom editor functionality, feel free to fork and rewrite with Naughty Attributes or similar.
Use the Package Manager and use Add package from git URL, using the following:
https://github.com/qhenshaw/GameEvents.git
Create a GameEventAsset of the desired type through:
Project View => Create => Events => [SomeType] Event Asset
There are two options for invoking GameEvents
-
Use the included
GameEventCallercomponent of the appropriate type. Select the desired Unity event to initiate, and assign the value andGameEventAsset. -
Reference the GameEventAsset and call its Invoke method:
[SerializeField] private TransformEventAsset _playerSpawnedEventAsset;
[SerializeField] private Transform _playerTransform;
private void Start()
{
_playerSpawnedEventAsset.Invoke(_playerTransform);
}There are again two options for subscribing to GameEvents
-
Use the included
GameEventListenercomponent of the appropriate type. Assign theGameEventAssetto listen to, and then theOnGameEventInvokedUnityEvent to add subscriber methods. -
Reference the GameEventAsset and add listeners to its OnInvoked event:
[SerializeField] private TransformEventAsset _playerSpawnedEventAsset;
private void OnEnable()
{
_playerSpawnedEventAsset.OnInvoked.AddListener(PlayerSpawned);
}
private void OnDisable()
{
_playerSpawnedEventAsset.OnInvoked.RemoveListener(PlayerSpawned);
}
private void PlayerSpawned(Transform player)
{
Debug.Log($"Player Spawned: {player.gameObject.name}");
}Additional GameEvent types can be added through an editor window found here:
Tools => Game Events => Create New Event Scripts
This tool will create the Asset, Caller, and Listener scripts all at once.