Events
A common way for mods to interact with Cubivox is with events. Events provide a way for mods to listen for user driven actions. For example, a player placing a voxel is an event.
Registering Events
Event handler functions are used to listen for events. The type of event that a function listen for is determined by its parameters.
public void OnVoxelPlace(VoxelPlaceEvent evt)
{
var playerName = evt.Player.GetName();
var voxelName = evt.Voxel.GetVoxelDef().GetName();
GetLogger().Info($"{playerName} placed the voxel {voxelName}!");
}
In the case above, the function will listen for the VoxelPlaceEvent. A mod can define an infinite amount of event handlers.
Here are a list of common events to listen for:
- VoxelPlaceEvent
- VoxelBreakEvent
- PlayerJoinEvent
- PlayerLeaveEvent
- PlayerMoveEvent
To register an event, you can call the RegisterEvent
method on the EventHandler. CubivoxMod
also provides a methods
register events.
public override void OnEnable()
{
RegisterEvent<VoxelPlaceEvent>(OnVoxelPlace);
RegisterEvent<VoxelBreakEvent>(OnVoxelBreak);
}
Cancellable Events
Some events are cancellable, such as the VoxelPlaceEvent. Cancellable events are triggered before an action occurs. When an event is canceled, the action does not occur. For example, canceling the VoxelPlaceEvent will prevent a voxel from being placed.
public void OnVoxelPlace(VoxelPlaceEvent evt)
{
evt.Cancel();
}
Events are executed in order of registration, some event handlers may be executed before you cancel the event.
Client/Server Only Events
Cubivox provides an easy way to make event handlers only be called on the client or server. To restrict
an event to a specific environment, all you need to do is add the [ClientOnly]
or [ServerOnly]
property.
[ServerOnly]
public void OnVoxelPlace(VoxelPlaceEvent evt)
{
var playerName = evt.Player.GetName();
var voxelName = evt.Voxel.GetVoxelDef().GetName();
GetLogger().Info($"{playerName} placed the voxel {voxelName}!");
}
Custom Events
Mods can define custom events by extending the Event
or any of its subclasses (such as CancellableEvent
).
Other mods can listen for these events by using the standard RegisterEvent
method.
class CustomEvent : Event {
}
You can trigger a custom event using the TriggerEvent
method.
CustomEvent evt = new CustomEvent();
Cubivox.GetEventManager().TriggerEvent(evt);