EventManager

EventManager is a singleton class that manages custom game events. An event is an occurrence of a specific action or condition that game can respond to.

Using the EventManager

You can use event manager to handle the game state and game events

To get game state use EventManager.GameStatus:

EventManager.GameStatus == EStatus.Play

To set game state use EventManager.SetGameStatus

EventManager.SetGameStatus(EStatus.Play);

The EventManager supports events with different argument types. There are different GetEvent methods that you can use to get a reference to the event of your choosing.

Subscribing to an event

To subscribe to an event, you first need to retrieve the event object using the GetEvent method, and then use the Subscribe method on the event, passing the function you want to be called when the event is triggered.

EventManager.GetEvent<BallCollectEventArgs>(EGameEvent.BallDestroyed).Subscribe(ShowExplosionEffect);

In this example, ShowExplosionEffect is a method in your class that matches the signature of the delegate type defined by the event. When the BallDestroyed event is triggered, ShowExplosionEffect will be called.

The method you subscribe should have the same argument types as the Event, for example, if the event is Event<BallCollectEventArgs> then the method you subscribe should take BallCollectEventArgs as an argument.

Unsubscribing from an event

It's good practice to unsubscribe from events when they're not needed, like when the object is disabled. This helps to prevent unwanted side effects and improve performance.

You can unsubscribe from an event in the same way you subscribe but use the Unsubscribe method instead.

EventManager.GetEvent<BallCollectEventArgs>(EGameEvent.BallDestroyed).Unsubscribe(ShowExplosionEffect);

In this example, ShowExplosionEffect will no longer be called when the BallDestroyed event is triggered.

Triggering an event

To trigger an event, you retrieve the event object using the GetEvent method and then use the Trigger method on the event, passing any arguments as required.

EventManager.GetEvent<BallCollectEventArgs>(EGameEvent.BallDestroyed).Invoke(ballCollectEventArgs);

In this example, ballCollectEventArgs is the data you want to send to all the subscribers when the BallDestroyed event is triggered.

Summary

The EventManager provides a powerful way to manage events in your game, and it's an important part of creating a flexible and modular game architecture. By subscribing, triggering, and unsubscribing to events, you can create a wide range of game behaviors without tightly coupling your game components.

Last updated