Observer Pattern in Unity with C# - by Jason Weimann

April 22, 2021

Observer Pattern

Game Dev Patterns


Title: Observer Pattern - Game Programming Patterns in Unity & C#
By: Jason Weimann
Youtube - Tutorial
Description: Introduction to the observer pattern and implementing it in Unity through C#.


Overview

This tutorial covers the basics of the observer pattern in game development with two ways of implementing it in Unity. The first approach is relatively simple just to establish the concept, whereas the second approach uses events with C# to create a more flexible system.

Observer Pattern Basics

An object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes (usually by calling one of their methods)

Example Uses in Games:
UI elements updating when data behind them changes
Achievement systems

Implementation #1: Inheriting Observer and Subject Classes

Observer Class:
Abstract class your observers will inherit from
OnNotify() method that accepts a value and notification type

Subject Class:
Abstract class your subjects will inherit from
Hold information on their list of observers they report to
RegisterObserver() method to add Observers to list of those reporting to
Notify() passes a value and notification type on to all the observers they report to in their list, in turn calling their OnNotify methods with the passed on data

This example gets the point across, but is not particularly well suited for Unity or C# projects. Requires a base class on all observers and subjects (although could possibly be changed to using an interface system).

Implementation #2: Using Events

Subject objects create a 'static event Action', which they then call when the requirements are met.

Observer objects have their own methods to perform when those same requirements are met, and they are connected by having the observers subscribe their relevant methods to that same 'static event'.

This reduces the direct coupling between the observers and subjects, as well as any other objects involved. Should profile this as calling events every frame can start to lead to performance loss. As always, also need to be careful to properly unsubscribe methods from events when needed (such as when deactivating or destroying objects).

Comments

Popular posts from this blog

Online Multiplayer Networking Solution Tutorial Using Unity and Mirror - Tutorial by: Jason Weimann

Exporting FBX from Houdini with Color

AStar for 2D Pathfinding in Unity