A common way to compose a game scene in Unity is attaching one GameObject to another to share methods and properties. This practice causes a highly coupled architecture that is hard to maintain. Unity does provide a Messaging System but it limits the parameter’s type that can be sent. In order to overcome these problems, I created a pure C# Event Manager to implement an event-driven architecture in my Unity Pixel Maze game.

Triggering events allow components to communicate with each other without a hard reference and to compose elaborated game scenes. In fact this Unity Event Manager exercises the essential ingredients of OOP (Object-Oriented Programming): message passing and encapsulation.

"OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things."

Alan Kay

How to Set up

In the first game scene, create an empty Unity GameObject 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.

EventManager.cs

How to Use

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 } 
  });

The Producer.cs and Consumer.cs classes below 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.

Producer.cs

Consumer.cs