This Gist represents an event-driven architecture that helps to structure my games in Unity. It uses events to trigger and communicate between decoupled parts of a game.
In the first game scene, create an empty Game Object named EventManager
and attach the EventManager.cs
script to it. This script is set to DontDestroyOnLoad
, i.e., it won't be destroyed when reloading scene.
The Producer.cs
and Consumer.cs
classes show how an event is published and consumed. In this example, when a coin is collected, an addCoins
event is published with the collected amount
. A Consumer receives the amount of coins collected and update its own coins amount.
- No parameter:
EventManager.TriggerEvent("gameOver", null);
- 1 parameter:
EventManager.TriggerEvent("gamePause", new Dictionary<string, object> { { "pause", true } });
- 2 or more parameters:
EventManager.TriggerEvent("addReward",
new Dictionary<string, object> {
{ "name", "candy" },
{ "amount", 5 }
});