Unity Observers

Hal Brooks
2 min readMar 10, 2022

Objective: Create cubes which have different responses to the same action.

Pressing space triggers an event that changes colors of the cubes based on their individual script.

Observers are game objects that listen for an event. Create a C# script called MainCamera and attach it to the Main Camera. This will house the public static event Action onSpace. The static key word means there is only one and event key word only allows methods that match the signature to subscribe, +=, or unsubscribe, -=, to the event. In this case, the onSpace Action signature has no parameters and returns no variables. The event trigger is monitored in void Update() for the pressing of the space key. If methods have been assigned, the ? after onSpace, these methods are Invoked.

The beauty of observers is that each object can have a unique script. For example when the space key is pressed some cubes will turn red, others green or blue. Since the color will be changed the MeshRenderer _renderer is assigned OnEnable() then subscribes a method, OnToggleColor, to the event MainCamera.OnSpace. The OnToggleColor() method checks if the current Color is not white changes the color to white, otherwise it changes the Color to red, green or blue depending on the individual script, shown below. To prevent memory leaks OnDisable() the OnToggleColor method is unsubscribed.

ColorCubeRed script is on three cubes, as is ColorCubeGreen and ColorCubeBlue.

This ability for the event to have a different response for different objects is known a polymorphism. Imagine if the cubes are enemies, some melee attack, others use a ranged attack or run away.