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:
- Subscribe those methods to an event, in this case we have the 'OnPlayerJump' event, wish is a member of the component EventManager.
- 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.
- Observer pattern: https://refactoring.guru/design-patterns/observer
- Delegates, events, actions: https://answers.unity.com/questions/1739085/when-to-decide-between-using-a-delegate-event-or-a.html
- Events: https://docs.microsoft.com/en-us/dotnet/standard/events/
- Actions: https://docs.microsoft.com/en-us/dotnet/api/system.action?view=netcore-3.1
- Delegates: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/
- Events in Unity: https://youtu.be/OuZrhykVytg
Special thanks to @AndersenCastaneda for introduced me to the topic.
Unity Developer. Passionate about: virtual reality, casual games, multiplayer.

