Using Attributes
SwiftlyS2 lets you register commands, events, and hooks by decorating methods with attributes, instead of wiring every handler manually.
Registration Scope
Attribute discovery runs on registered object instances:
- Your plugin class (the one inheriting
BasePlugin) is registered automatically. - Any other class must be registered explicitly with
Core.Registrator.Register(instance)(APIIRegistratorService).
public sealed class ModerationHandlers
{
[ClientChatHookHandler]
public HookResult OnClientChat(int playerId, string text, bool teamonly)
{
if (text.Contains("badword", StringComparison.OrdinalIgnoreCase))
{
return HookResult.Stop;
}
return HookResult.Continue;
}
}
public override void Load(bool hotReload)
{
Core.Registrator.Register(new ModerationHandlers());
}Register each handler instance once - registering the same instance
repeatedly duplicates callbacks. APIIRegistratorService exposes
only Register(object instance), so there's no unregister call to pair it with.
Signature Rules
Attribute-decorated methods must match the expected delegate: same parameter order/types, same return type (void vs HookResult), and same generic event/message type where the attribute is generic. Otherwise the handler won't be picked up.
Attributes either carry their configuration as constructor arguments ([Command], [CommandAlias], [GameEventHandler], [GameHookHandler], [EntityOutputHandler], [EntityInputHandler]) or are parameterless ([ClientCommandHookHandler], [ClientChatHookHandler], the net-message handlers). Where the handler type comes from a type parameter or from the method's parameter - [EventListener<T>], [GameEventHandler], the net-message handlers - that type is the only thing saying which event or message the method serves.
Attribute Reference
Valid target is where each attribute goes; all of them allow one instance per target (AllowMultiple = false), except APICommandAlias:
| Attribute | Valid target | Handler signature |
|---|---|---|
| APIPluginMetadata | plugin class | - |
| APICommand | method | void (ICommandContext context) |
| APICommandAlias | method carrying [Command] | same signature as [Command] on that method |
| APIGameEventHandler | method | HookResult (TEvent eventObj) |
| APIEventListener`1 | method | the signature of delegate T |
| APIGameHookHandler | method | the hooked delegate, e.g. void (ref TakeDamageEntityPreContext ctx) |
| APIClientCommandHookHandler | method | HookResult (int playerId, string commandLine) |
| APIClientChatHookHandler | method | HookResult (int playerId, string text, bool teamonly) |
| APIServerNetMessageHandler | method | HookResult (T msg) |
| APIServerNetMessageInternalHandler | method | HookResult (T msg, int playerId) |
| APIClientNetMessageHandler | method | HookResult (T msg, int playerId) |
| APIEntityOutputHandlerAttribute / APIEntityOutputHandlerAttribute`1 | method | void (IOnEntityFireOutputHookEvent @event) |
| APIEntityInputHandlerAttribute / APIEntityInputHandlerAttribute`1 | method | void (IOnEntityIdentityAcceptInputHookEvent @event) |
APIPluginMetadata
On your plugin class. Id and Version are required; the rest optional - Name falls back to Id and MinimumAPIVersion defaults to "0.0.0". See Getting Started for the defaults of every property:
[PluginMetadata(Id = "my.plugin", Version = "1.0.0", Name = "My Plugin", Author = "Author", Description = "...", Website = "...")]
public partial class MyPlugin : BasePlugin
{
}APICommand
Registers a chat/console command. The method must match ICommandService.CommandListener (void (ICommandContext context)), and the attribute takes (name, registerRaw = false, permission = "", helpText = "SwiftlyS2 registered command"):
nameis the command name as typed by the user - it registers assw_<name>unlessregisterRawistrue.registerRawregisters the name as-is, without thesw_prefix.permissionis checked through Permissions before the handler runs.helpTextis the description shown in command listings.
Name, RegisterRaw, Permission and HelpText are settable properties as well, so [Command("heal", HelpText = "Heals yourself")] works too. A method can carry only one [Command] (AllowMultiple = false) - extra names go through APICommandAlias below. Full registration/lookup API on APIICommandService - see Commands.
[Command("heal", permission: "myplugin.heal", helpText: "Heals yourself")]
public void OnHealCommand(ICommandContext context)
{
var player = context.Sender;
}APICommandAlias
Adds an alternate name for the command registered by the [Command] on the same method. Takes (alias, registerRaw = false), both also exposed as the settable properties Alias and RegisterRaw:
[Command("heal")]
[CommandAlias("hp")]
[CommandAlias("h")]
public void OnHealCommand(ICommandContext context)
{
// reachable as sw_heal, sw_hp and sw_h
}AllowMultiple = true, so stack one attribute per extra name; registerRaw must match how the command name itself was registered. This is the attribute-based equivalent of APIICommandService.RegisterCommandAlias.
APIGameEventHandler
Hooks a generated game event (EventPlayerDeath, EventRoundStart, ...). Takes (hookMode), where HookMode.Pre runs before the game processes the event and HookMode.Post after, and the method must match IGameEventService.GameEventHandler<T> (HookResult (T eventObj)) for the event type you want - see APIIGameEventService and Game Events for the full hook/fire API:
[GameEventHandler(HookMode.Post)]
private HookResult OnPlayerDeath(EventPlayerDeath @event)
{
return HookResult.Continue;
}APIEventListener`1 ([EventListener<T>])
Subscribes a method to one of the framework's own events. T must be a delegate on APIEventDelegates, which mirror APIIEventSubscriber (e.g. EventDelegates.OnEntityCreated), and the method must match that delegate's signature:
[EventListener<EventDelegates.OnEntityCreated>]
public void OnEntityCreated(IOnEntityCreatedEvent @event)
{
}The attribute is parameterless and allows one per method (AllowMultiple = false) - use += when a single method has to listen to several events. This is the attribute-based equivalent of Core.Event.OnEntityCreated += OnEntityCreated;, see Core Events.
APIGameHookHandler
Hooks one of the Pre/Post callbacks exposed by a category under APIIGameHooks (e.g. entity take-damage). Takes (hookMode), and the method signature has to match the delegate of the hook you want - for Core.GameHooks.Entities.TakeDamage.Pre that is void (ref TakeDamageEntityPreContext ctx):
[GameHookHandler(HookMode.Pre)]
private void OnTakeDamagePre(ref TakeDamageEntityPreContext ctx)
{
ref var info = ref ctx.Params.Info;
// ctx.SetHookResult(HookResult.Stop); // blocks the damage
}Game-hook callbacks take the result on the context via SetHookResult(HookResult) instead of returning it, see Native Functions and Hooks.
APIClientCommandHookHandler
Intercepts a raw client console command before the server processes it. Parameterless; the method must match ICommandService.ClientCommandHandler (HookResult (int playerId, string commandLine)) - see APIICommandService.HookClientCommand:
[ClientCommandHookHandler]
public HookResult OnClientCommand(int playerId, string commandLine)
{
return HookResult.Continue;
}APIClientChatHookHandler
Intercepts a chat message before it's broadcast. Parameterless; the method must match ICommandService.ClientChatHandler (HookResult (int playerId, string text, bool teamonly)) - see APIICommandService.HookClientChat:
[ClientChatHookHandler]
public HookResult OnClientChat(int playerId, string text, bool teamonly)
{
return HookResult.Continue;
}Returning HookResult.Stop from a chat hook drops the message and skips the remaining hooks, so use it deliberately.
APIEntityOutputHandlerAttribute / APIEntityOutputHandlerAttribute`1
Hooks an entity I/O output by designer name, or generically by schema class (<T> resolves T.ClassName for you, and throws ArgumentException when T has no designer name). The non-generic form takes (designerName, outputName), the generic one (outputName); both are exposed as the settable properties DesignerName and OutputName:
[EntityOutputHandler("func_door", "OnOpen")]
public void OnDoorOpened(IOnEntityFireOutputHookEvent @event)
{
Console.WriteLine($"Output '{@event.OutputName}' fired by '{@event.DesignerName}'");
}
[EntityOutputHandler<CBaseDoor>("OnOpen")]
public void OnDoorOpenedGeneric(IOnEntityFireOutputHookEvent @event)
{
}Set @event.Result = HookResult.Stop to block the output from firing.
APIEntityInputHandlerAttribute / APIEntityInputHandlerAttribute`1
Same shape as the output handler, for entity I/O inputs instead - (designerName, inputName) or the generic <T>(inputName), with the input name in place of the output name. DesignerName and InputName are the settable properties, and the generic form resolves DesignerName from T.ClassName the same way:
[EntityInputHandler("func_door", "Open")]
public void OnDoorOpenInput(IOnEntityIdentityAcceptInputHookEvent @event)
{
Console.WriteLine($"Input '{@event.InputName}' accepted by '{@event.DesignerName}'");
}
[EntityInputHandler<CBaseDoor>("Open")]
public void OnDoorOpenInputGeneric(IOnEntityIdentityAcceptInputHookEvent @event)
{
}Set @event.Result = HookResult.Stop to block the input from being accepted.
APIServerNetMessageHandler
Hooks a net message the server sends to clients. Parameterless - the message type comes from the method parameter, which must satisfy the same constraints as the programmatic hook delegate (ITypedProtobuf<T>, INetMessage<T> and IDisposable, which every generated message does) - see APIINetMessageService and Net Messages:
[ServerNetMessageHandler]
public HookResult OnServerSound(CMsgSosStartSoundEvent msg)
{
Console.WriteLine($"sound hash={msg.SoundeventHash}");
return HookResult.Continue;
}APIServerNetMessageInternalHandler
Same as APIServerNetMessageHandler, but for internal server messages, whose handler also receives the target playerId:
[ServerNetMessageInternalHandler]
public HookResult OnServerSoundInternal(CMsgSosStartSoundEvent msg, int playerId)
{
Console.WriteLine($"player={playerId}, sound hash={msg.SoundeventHash}");
return HookResult.Continue;
}APIClientNetMessageHandler
Hooks a net message a client sends to the server, with the sending playerId:
[ClientNetMessageHandler]
public HookResult OnClientMove(CCLCMsg_Move msg, int playerId)
{
Console.WriteLine($"player={playerId}, lastCmd={msg.LastCommandNumber}");
return HookResult.Continue;
}See Net Messages and
Entity for the programmatic
(Core.NetMessage/Core.EntitySystem) equivalents of the attributes above.
Related Attributes
Two more attributes are applied by plugins but don't register handlers: APISwiftlyInject on a field or property, which makes SwiftlyS2 inject the matching service into that member (see Getting Started), and APIThreadUnsafeAttribute, which annotates framework APIs that must only run on the game thread (see Thread Safety).
Not every type named like an attribute is one: APITraceCollisionAttributes describes the collision shape of a trace hit and is read from APITraceResult (ShapeAttributes), not applied to your code.