Using events to communicate with manager scripts — observer pattern

Instance of DogListener Marcin Moskala

In the Space shooter project that I’m working on, when the player destroys an enemy, it communicates with the UI manager to update the score. Code looks like this:

This is a good approach. However, I wanted to implement the same using Action events of Observer pattern.

Some terms to clarify:

Event sender: class that declares the event

Event raiser: method that “fires” the event

Event listener: class that subscribes to the event

Event handler: method that is implemented or executed when the event is “fired”

In this case, Player.cs will be the event sender that will raise the OnPlayerScored Action event when the AddScore method is called.

When is AddScore method called? In Laser.csOnTriggerEnter2D

Declare an Action event in player that will include the int scorevalue as parameter

Now we will subscribe the UIManager class to this event. At that point, this class will be a Listener that will handle the event with its own method implementation( UpdateScore( ) )

Why is it meaningful?

Because it implements what in coding is called Loose coupling or decoupled code.

In this example, let’s imagine we changed the name to the UIManager. The reference to it will be broken, and the code will need to be refactored.

With the observer pattern, the Player.cs script just sends a “message” (raises an event) to all scripts to check if any is subscribed to the event. If so, the Listener class (subscriber) will execute its own method implementation.

In the last case, no matters if the script’s name was changed. Player.cs doesn’t care about any name, it cares about which scripts are subscribed. That’s all.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store