Observer Design Pattern in Unity

David Brown
2 min readDec 20, 2021

--

Objective: Turn all cubes to the color red no matter how many cubes are on screen.

The observer pattern is a design pattern that allows an object to notify other objects about changes in their state. This requires the use of delegates and events or an action. In our example, if we press spacebar, we want to notify all the cubes to turn red.

Why use the observer pattern

When normally programming this feature, you would use a foreach loop to turn every cube red. This works but it's not performant. How would you like it if you wanted everyone to go to the party, but you have to go to every person's house to tell them? Instead, when we want everyone to go to the party, the people that care will go without us having to go to every house.

Observer Version

In the player script, we need to create an action and raise the event when we press spacebar.

Now anything that cares about that event will do something.

In our case, the cubes care about this event. The cubes will subscribe to the event once spawned in. When the event is raised, the cubes turn red. However, if the cubes get destroyed or disabled, they will unsubscribe from the event, so it won’t cause errors.

Now no matter how many cubes are in the scene, they will always turn red

Like this article or the baby will delete your computer files

--

--

David Brown

I like pizza, cream soda, and making games with Unity