Publisher -> Subscriber
Last updated
Last updated
Publisher-subscriber is a design pattern commonly used in game development. This pattern allows an object to publish information to other objects that subscribe to the object. Objects that publish information are called "publishers", while objects that receive information are called "subscribers".
Publisher-subscribers provide an advantage in game development because they allow communication between isolated objects. This is especially useful if the objects have dependencies on one another, but there is no need to know in detail how the other objects work.
A simple example is if in your game there is an event which if the event is executed, then many other elements in your game will react to that event. For example, when the player character dies, you want to play the game over audio, display the game over screen, submit the player's score to the leaderboard, etc. You can run all these methods in one script but it will create coupling and dependencies in your script. This is where this pattern is used.
You just need to send an event/message from your player script when the player dies, and you can just make the script that needs to react to the event to become a subscriber.
Gamepangin has provided an event that accepts a string as a parameter in the GameEvent.cs script If you only need to send an event that only contains the string: eventName, you can immediately use this GameEvent. The following is the contents of GameEvent.cs
There are 2 ways to send an event, namely by EventManager.TriggerEvent or directly via the static Trigger method of an event struct.
So that your script can find out what specific events are sent, you must subscribe to the event by adding the IEventListener interface and also don't forget to tell the EventManager to subscribe/unsubscribe this component.
You can see the GameEvent example above to create your own event that can receive the parameters you want, here is an example of ApplicationEvent.cs which is included in Gamepangin which you can also use to detect whether your game is running in the background or not