Skip to content

Using C# Events (P2)

Beryl edited this page Feb 10, 2025 · 3 revisions

Before using events

Before using events, you will have to subscribe your handlers to the desired events. There are currently two ways of registering events in LabAPI.

  • C# Events, demonstrated in these examples.
  • Custom Event Handlers, demonstrated in their own special section.

You can choose the one you like the most. Meanwhile, a custom events handler may be easier to work with for beginners, legacy events can give more freedom in the development stage.

Using events

Each event has a different usage. Whenever you subscribe a method to an event it should have an event argument parameter following the next example:

void OnWaveRespawned(WaveRespawnedEventArgs args)
{
    // Your code 
}

Some events don't have any type of argument, these events include ServerEvents.RoundStarted, ServerEvents.WaitingForPlayers...

Using the arguments

Each argument has different properties you may use for your advantage

Some event arguments have a special property: IsAllowed which allows events to be cancelled:

void OnPlayerChangingRole(PlayerChangingRoleEventArgs args)
{
    args.IsAllowed = false;
    // The player role won't change!
}

Cancellable events usually end with -ing

All the properties in the event arguments that have setters can be freely edited.

void OnPlayerChangingRole(PlayerChangingRoleEventArgs args)
{
    // PlayerChangingRoleEventArgs.NewRole has a setter.
    args.NewRole = RoleTypeId.Tutorial;
    // In this case example, if I set it to Tutorial
    // it will always set the player role to Tutorial when it changes!
}

Wow! You learn fast. That is all events provide, go ahead and test them out!

Clone this wiki locally