Skip to content

✨📌 Simple observer pattern example in Unity to achieve decoupled code when many components must response to an event of the app/game

Notifications You must be signed in to change notification settings

dikarkik/observer_pattern

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

observer_pattern

Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.

In this example we want decoupled code for a Player that Jumps, so we made a component for every aspect of the 'Jump' feature: PlayerAnimation, PlayerPhysics and AudioManager. To keep this simple, those components just have an method called 'Jump' to print a message on the console. To Invoke all those methods when the user pess the Space bar key we need to achieve two things:

  1. Subscribe those methods to an event, in this case we have the 'OnPlayerJump' event, wish is a member of the component EventManager.

Diagram subscribe

  1. Invoke that event when the Space bar key is pressed, we do this since the component InputManager calling a method inside the EventManager which Invoke the 'OnPlayerJump' event.

Diagram invoke

Documentation:

Special thanks to @AndersenCastaneda for introduced me to the topic.

About me:

Unity Developer. Passionate about: virtual reality, casual games, multiplayer.

About

✨📌 Simple observer pattern example in Unity to achieve decoupled code when many components must response to an event of the app/game

Topics

Resources

Stars

Watchers

Forks