Reacting to Game Events in CounterStrikeSharp
Game events are messages the game sends when something happens: a player dies, a round starts, a bomb is planted. Most plugins that do something interesting are built from them. In CounterStrikeSharp subscribing to an event takes only a few lines.
What an event is
Each event has its own class with a name that starts with Event, such as EventPlayerDeath or EventRoundStart, and each carries data about what happened, like who died and who killed them. Your plugin gets a handler method called every time the event happens.
Subscribe with an attribute
The simplest way is the GameEventHandler attribute on a method. The method receives the event and returns a HookResult. The event data is read straight from the event object.
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using Microsoft.Extensions.Logging;
public class EventsPlugin : BasePlugin
{
public override string ModuleName => "Events Example";
public override string ModuleVersion => "1.0.0";
[GameEventHandler] public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) {
Logger.LogInformation("{Name} died", @event.Userid?.PlayerName);
return HookResult.Continue;
}
}
Subscribe in code
You can also register a handler in the Load method with RegisterEventHandler. It does the same thing, and is better when you want to subscribe only under some condition, for example depending on the config.
public override void Load(bool hotReload)
{
RegisterEventHandler<EventRoundStart>((@event, info) =>
{
Logger.LogInformation("Round started");
return HookResult.Continue;
});
}
Pre and Post
By default your handler runs after the game has processed the event (Post). With HookMode.Pre it runs before, which lets you change what happens, for example hiding the default message with DontBroadcast. Use Post unless you really need to interfere.
[GameEventHandler(HookMode.Pre)]
public HookResult OnPlayerDeathPre(EventPlayerDeath @event, GameEventInfo info)
{
if ([email protected])
{
info.DontBroadcast = true;
}
return HookResult.Continue;
}
Players can be null
Event properties like Userid can be empty, for example when the player left just as the event fired, or when the killer is the world itself. Always check for null before you use them, otherwise one unlucky moment throws an exception in the middle of a round.
What HookResult means
Continue lets the game carry on normally, and it is the right answer most of the time. Handled tells the game you took care of it, and Stop stops other handlers from running. Return Continue unless you have a reason to do otherwise.
Good habits
Handlers run on the game thread, so keep them fast and never wait for a database or a web request inside one. There is no need to unsubscribe when the plugin unloads, CounterStrikeSharp removes the handlers for you. For the list of events and their fields, check the game event documentation.
Was this tutorial useful?
Barlap for the community.