Using the EventBus
In this guide you will learn how to subscribe to events using EventBus.
What are events?
Event is a piece of code that runs when a certain action happens in the game. Whether it's opening a new window, a player changing the map, unlocking an achievement - these are all events.
Full list of all events you can see here.
Why are events important?
Events allow developers to react to changes in the game, providing more flexible gameplay management and the ability to introduce new features without changing the game code.
Event Subscription
To subcribe to an event, you need to use the Subscribe
method of the EventBus
class. Below is an example that demonstrates how to do this.
Let's assume that you want to subscribe to an event related to new item being added to the player's inventory. You can subscribe to this event as follows:
public void OnLoad(ModContext context)
{
EventBus.Subscribe<ItemAddedEvent>(OnItemAdded); // subscribing to an event while mod is loading
}
private void OnItemAdded(ItemAddedEvent e)
{
// here we can, for example, get item's ID and name.
context.Logger.Log(e.ItemName);
context.Logger.Log(e.ItemID.ToString());
}
Explanation
- Subscribing to an event: When the mod is loading, we subscribe to an event called
ItemAddedEvent
by passing theOnItemAdded
method, which will be called every time the player has a new item in their inventory. - Event Handling: Method
OnItemAdded
accepts the event object and executes the necessary logic. In this case, we output item's name and ID.
Unsubscribing from an event
If you think you won't need an event anymore, you can unsubscribe from that event. It is enough to call Unsubscribe
method at the moment you need it:
public void OnShutdown()
{
EventBus.Unsubscribe<ItemAddedEvent>(OnItemAdded);
}
Here, we unsubscribe the OnItemAdded
method from event called ItemAddedEvent
when the game is shutting down.