swiftlys2/docs/api/releases/features/ai/

Porting from CounterStrikeSharp

This guide will help you migrate your existing CounterStrikeSharp plugins to SwiftlyS2. We'll cover the key differences between the frameworks and provide side-by-side examples to make the transition as smooth as possible.

Both frameworks share a lot of the same underlying concepts (game events, schema access, virtual function hooking), so most of the migration work is renaming calls to their SwiftlyS2 equivalent rather than rethinking your plugin's logic.

Overview

SwiftlyS2 introduces several key improvements over CounterStrikeSharp:

  • Modern .NET 10 - Takes advantage of the latest .NET features and performance improvements
  • Improved API Design - More intuitive and consistent API structure, split into discrete Core.* services
  • Built-in Menu System - Component-based menus (buttons, toggles, sliders, inputs) via Core.Menu, no extra dependency needed
  • Built-in Game Hooks - Typed hooks for common native functions (damage, movement, item pickup, ...) via Core.GameHooks
  • Database Abstraction - Global connection configuration shared across plugins
  • Per-Plugin GameData - Each plugin manages its own signatures/offsets instead of relying on a shared gamedata file
  • Cross-Plugin Interfaces - A capability-style system for exposing and consuming APIs between plugins

Migration Checklist

Before starting your migration, ensure you have:

  • .NET 10.0 SDK installed
  • Your existing CounterStrikeSharp plugin source code
  • Understanding of your plugin's dependencies
  • Test environment set up for SwiftlyS2

Project Setup

Package Reference

<PackageReference Include="CounterStrikeSharp.API" Version="1.0.3" />

Version patterns:

  • 1.0.3 - Specific version
  • * - Latest stable release
  • *-* - Latest preview/pre-release version

Target Framework

<TargetFramework>net8.0</TargetFramework>

SwiftlyS2 requires .NET 10.0 or later. Make sure you have the appropriate SDK installed.

Plugin Class

Base Structure

public class MyPlugin : BasePlugin
{
    public override string ModuleName => "My Plugin";
    public override string ModuleVersion => "1.0.0";
 
    public override void Load(bool hotReload)
    {
    }
}

SwiftlyS2 also calls OnAllPluginsLoaded() once every plugin has finished loading - useful if you need another plugin's shared interface to already be registered before you use it.

Event Handling (Game Events)

RegisterEventHandler<EventPlayerDeath>(OnPlayerDeath);
RegisterEventHandler<EventPlayerDeath>(OnPlayerDeath, HookMode.Pre);

Manual Registration

In SwiftlyS2, you can also register event handlers manually, typically in Load():

// SwiftlyS2 - manual registration in Load()
Guid postHookId = Core.GameEvent.HookPost<EventPlayerDeath>(OnPlayerDeath);
Guid preHookId = Core.GameEvent.HookPre<EventPlayerDeath>(OnPlayerDeathPre);
 
// Unhook later, e.g. in Unload()
Core.GameEvent.Unhook(postHookId);

Event Handler Signature

private HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info)
{
    var player = @event.Userid;
    return HookResult.Continue;
}

In SwiftlyS2, the GameEventInfo parameter is removed. Event fields are read through typed properties, or through @event.Accessor if a typed property is inexistent.

Getting Player from Event

var player = @event.Userid;
var attacker = @event.Attacker;

Player Operations

Getting All Players

var players = Utilities.GetPlayers();

Player Properties

var isValid = player.IsValid;
var name = player.PlayerName;
var steamId = player.SteamID;

Sending Messages

// Send to specific player
player.PrintToChat("message");
 
// Send to all players
Server.PrintToChatAll("message");

Additional Message Types

SwiftlyS2 provides multiple message methods for enhanced communication:

// Additional message types in SwiftlyS2 (also available per-player on IPlayer)
Core.PlayerManager.SendCenter("center message");
Core.PlayerManager.SendAlert("alert message");
Core.PlayerManager.SendConsole("console message");
Core.PlayerManager.SendCenterHTML("<b>HTML</b>", duration: 5000); // duration in milliseconds
Core.PlayerManager.SendNotify("notify message");
Core.PlayerManager.SendChatEOT("chat message, end-of-turn");

Each of these also has an *Async variant (for example SendChatAsync) that is safe to call from other threads, and a generic SendMessage(MessageType, ...) overload.

Chat Colors

SwiftlyS2 uses square brackets instead of curly braces for colors:

$"{ChatColors.Red}Red text {ChatColors.Green}Green text"

See the Chat & CenterHTML Styling guide for the full color list.

Timers & Scheduling

SwiftlyS2's tick-based Delay overload uses game ticks as the unit. Use the *BySeconds variants for time-based delays.

AddTimer(5.0f, () => { /* code */ });
AddTimer(1.0f, () => { /* code */ }, TimerFlags.REPEAT);
Server.NextFrame(() => { /* code */ });
Server.NextWorldUpdate(() => { /* code */ });

Both Delay and DelayAndRepeatBySeconds return a CancellationTokenSource you can use to cancel the scheduled task early.

CounterStrikeSharp's TimerFlags.STOP_ON_MAPCHANGE has no flag equivalent. Instead, pass the token to StopOnMapChange. Plain repeating timers (without an initial delay) are also available:

var cts = Core.Scheduler.RepeatBySeconds(1, () => { /* code */ }); // every second
Core.Scheduler.Repeat(64, () => { /* code */ });                   // every 64 ticks
Core.Scheduler.StopOnMapChange(cts);                               // cancel automatically on map change

Commands

Basic Command Registration

[ConsoleCommand("css_mycommand", "Description")]
public void OnMyCommand(CCSPlayerController? player, CommandInfo command)
{
}

Admin Commands

In CounterStrikeSharp, permissions are declared with a separate [RequiresPermissions] attribute. In SwiftlyS2, permissions are part of the Command attribute itself:

[Command("admincommand", permission: "admin.permission")]
public void OnAdminCommand(ICommandContext context)
{
    // Only players with admin.permission can use this command
}

Command Aliases

SwiftlyS2 provides a clean way to register command aliases:

// Register primary command with aliases
Core.Command.RegisterCommand("mycommand", OnMyCommand);
Core.Command.RegisterCommandAlias("mycommand", "mc");
Core.Command.RegisterCommandAlias("mycommand", "mycmd");

Permissions

CounterStrikeSharp ships a full admin framework (admins.json, admin_groups.json, immunity, overrides). SwiftlyS2's built-in permission manager is intentionally simpler - a flat, wildcard-aware permission store keyed by SteamID that plugins (or an admin plugin built on top of it) can manage.

bool isAdmin = AdminManager.PlayerHasPermissions(player, "@css/ban");

Command's permission parameter checks against this same permission store, so you rarely need to call Core.Permission directly inside a command handler.

SwiftlyS2 has a built-in, component-based menu system, available through Core.Menu. Menus are made of components (buttons, toggles, sliders, inputs, submenus, ...) and drawn by a renderer, so the server owner can switch between centre-screen HTML and chat output without any plugin change.

Core.MenusAPI (the classic menu builder) is obsolete and will be removed in a future version. Use Core.Menu for all new code. See the Menu System page for the full reference.

Creating a Menu

var menu = new ChatMenu("Title");
menu.AddMenuOption("Option 1", (p, o) => { });
MenuManager.OpenChatMenu(player, menu);

Menu ids are namespaced by convention ("myplugin.shop"), because the id is also what server owners use to configure key binds, renderer and input method per menu. A player can only have one menu open at a time, so opening a menu replaces the previous one.

Available components include TextComponent, ButtonComponent, ToggleComponent, SliderComponent, ChoiceComponent, SelectorComponent<T>, InputComponent, SubmenuComponent, ProgressBarComponent, DividerComponent and SpacerComponent.

Closing Menus

MenuManager.CloseActiveMenu(player);

Menus opened by your plugin are closed automatically when it unloads, so you don't need to track them yourself in Unload().

Cross-Plugin Capabilities

CounterStrikeSharp lets plugins expose an API to each other through PluginCapability<T>. SwiftlyS2 has the same idea built directly into BasePlugin, backed by IInterfaceManager.

// Provider plugin
public static readonly PluginCapability<IMyPluginApi> Capability = new("my_plugin:api");
Capabilities.RegisterPluginCapability(Capability, () => new MyPluginApi());
 
// Consumer plugin
var api = MyPluginProvider.Capability.Get();

The shared interface type (IMyPluginApi above) must live somewhere both plugins can reference, e.g. a small shared contracts assembly - the same requirement CounterStrikeSharp has for PluginCapability&lt;T&gt; interfaces.

Entity Operations

Finding Entities

Utilities.FindAllEntitiesByDesignerName<CPlantedC4>("planted_c4");

Modifying Schema Values

In CSS you need to call SetStateChanged after modifying networked properties. In SwiftlyS2 every networked schema field gets a generated <FieldName>Updated() method instead.

player.PlayerPawn.Value.Health = 100;
Utilities.SetStateChanged(player.PlayerPawn.Value, "CBaseEntity", "m_iHealth");

Configuration

SwiftlyS2 uses the .NET Options pattern with support for JSON, JSONC, and TOML files with hot-reload capability.

Loading Configuration

// SwiftlyS2
private PluginConfig _config = null!;
 
private void LoadConfiguration()
{
    const string ConfigFileName = "config.json";
    const string ConfigSection = "MyPlugin";
 
    // Initialize config file from model (creates file with defaults if not exists)
    Core.Configuration
        .InitializeJsonWithModel<PluginConfig>(ConfigFileName, ConfigSection)
        // Configure the config source with hot-reload support
        .Configure(cfg => cfg.AddJsonFile(
            Core.Configuration.GetConfigPath(ConfigFileName),
            optional: false,
            reloadOnChange: true)); // auto-reload on file change
 
    // Build service provider with options pattern
    ServiceCollection services = new();
    services.AddSwiftly(Core)
        .AddOptionsWithValidateOnStart<PluginConfig>()
        .BindConfiguration(ConfigSection);
 
    var provider = services.BuildServiceProvider();
    _config = provider.GetRequiredService<IOptions<PluginConfig>>().Value;
}

Config Model Example

public sealed class PluginConfig
{
    public string DatabaseConnection { get; set; } = "";
    public int MaxPlayers { get; set; } = 10;
    public bool EnableFeature { get; set; } = true;
}

The generated config.json will look like:

{
    "MyPlugin": {
        "DatabaseConnection": "",
        "MaxPlayers": 10,
        "EnableFeature": true
    }
}

See the Dependency Injection guide for more on services.AddSwiftly(Core).

Database

CounterStrikeSharp leaves database access entirely up to the plugin (usually Dapper/MySqlConnector with a connection string in the plugin's own config). SwiftlyS2 has a global database configuration system instead - connections are defined once in configs/database.jsonc and referenced by name from any plugin.

Supported databases: MySQL, PostgreSQL, SQLite

Global Configuration

Create a configs/database.jsonc file in your SwiftlyS2 installation:

{
    "default_connection": "host",
    "connections": {
        "host": "mysql://username:password@localhost:3306/database"
    }
}

Connection string formats:

  • MySQL: mysql://user:pass@host:3306/database
  • PostgreSQL: postgresql://user:pass@host:5432/database
  • SQLite: sqlite://path/to/database.db

Using in Plugins

// Plugin config references connection by name
public sealed class PluginConfig
{
    public string DatabaseConnection { get; set; } = "host"; // name from database.jsonc
}
 
// Get connection using the name
using var connection = Core.Database.GetConnection(_config.DatabaseConnection);
connection.Open();
 
// Use with Dapper or any ADO.NET approach
await connection.ExecuteAsync("SELECT * FROM players WHERE steamid = @SteamId", new { SteamId = steamId });

Translations

File Location

lang/en.json

Usage

// Server language
Localizer["key"]
Localizer["key", arg1, arg2]
 
// Player language
Localizer.ForPlayer(player, "key")
Localizer.ForPlayer(player, "key", arg1, arg2)

Logging

Logger.LogInformation("Loaded {Plugin}", ModuleName);

Core.Logger is a standard Microsoft.Extensions.Logging.ILogger, and Core.LoggerFactory is available if you need to create scoped loggers for other classes.

Project File (.csproj)

Full example with comments:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <!-- SwiftlyS2 requires .NET 10 -->
    <TargetFramework>net10.0</TargetFramework>
    <!-- Enable modern C# features -->
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <LangVersion>latest</LangVersion>
    <!-- Required for schema access -->
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
    <!-- Use filename as namespace and assembly name -->
    <RootNamespace>$(MSBuildThisFileName)</RootNamespace>
    <AssemblyName>$(MSBuildThisFileName)</AssemblyName>
    <!-- Disable auto-generated assembly info -->
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
    <!-- Performance optimization -->
    <TieredCompilation>true</TieredCompilation>
    <!-- Copy dependencies to output -->
    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
    <!-- Output to build folder -->
    <OutputPath>$(MSBuildThisFileDirectory)build/</OutputPath>
    <PublishDir>$(OutputPath)publish/$(MSBuildThisFileName)</PublishDir>
  </PropertyGroup>
 
  <ItemGroup>
    <!-- SwiftlyS2 package - use *-* for latest preview, * for stable -->
    <PackageReference Include="SwiftlyS2.CS2" Version="*-*" ExcludeAssets="runtime" PrivateAssets="all" />
    <!-- Copy resources folder to output (translations, configs, etc.) -->
    <None Update="resources\**\*.*" CopyToOutputDirectory="PreserveNewest" />
  </ItemGroup>
 
  <!-- Optional: Create zip after publish -->
  <Target Name="CreateZip" AfterTargets="Publish">
    <ZipDirectory SourceDirectory="$(PublishDir)../" DestinationFile="$(OutputPath)../$(AssemblyName).zip" Overwrite="true" />
  </Target>
</Project>

ConVars

Finding and Reading ConVars

var convar = ConVar.Find("mp_round_restart_delay");
var value = convar?.GetPrimitiveValue<float>();

Setting ConVar Values

var convar = ConVar.Find("mp_warmup_time");
convar?.SetValue(30);

Creating Plugin ConVars

CounterStrikeSharp exposes this through the [ConVar] attribute on a field. SwiftlyS2 creates (or reuses) one imperatively:

[ConVar("my_plugin_enabled", "Enables the plugin", ConVarFlags.FCVAR_NONE)]
public bool Enabled { get; set; } = true;

Listeners

SwiftlyS2 uses typed event handlers with strongly-typed event parameters.

Client Events

RegisterListener<Listeners.OnClientConnect>((slot, name, ip) => { });
RegisterListener<Listeners.OnClientDisconnect>((slot) => { });
RegisterListener<Listeners.OnClientAuthorized>((slot, steamId) => { });

Map Events

RegisterListener<Listeners.OnMapStart>((mapName) => { });
RegisterListener<Listeners.OnMapEnd>(() => { });

Entity Events

RegisterListener<Listeners.OnEntityCreated>((entity) => { });
RegisterListener<Listeners.OnEntitySpawned>((entity) => { });
RegisterListener<Listeners.OnEntityDeleted>((entity) => { });

Entity Take Damage

Core.Event.OnEntityTakeDamage still exists but is deprecated. Use Core.GameHooks.Entities.TakeDamage instead, which gives you separate Pre/Post hooks and direct access to the native damage info.

private void OnTakeDamagePre(ref TakeDamageEntityPreContext ctx)
{
    var entity = ctx.Params.Entity;
    ref var info = ref ctx.Params.Info;
    // inspect/modify info, then optionally: ctx.SetHookResult(HookResult.Stop);
}
 
// Register in Load():
Core.GameHooks.Entities.TakeDamage.Pre += OnTakeDamagePre;

Other Useful Events

// SwiftlyS2 additional events
private void OnTick() { } // every server tick (hot path!)
private void OnWorldUpdate() { } // every world update, even in hibernation
private void OnPrecacheResource(IOnPrecacheResourceEvent @event) { @event.AddItem("path/to/resource.vmdl"); }
 
// Register in Load():
Core.Event.OnTick += OnTick;
Core.Event.OnWorldUpdate += OnWorldUpdate;
Core.Event.OnPrecacheResource += OnPrecacheResource;

Player Movement

Teleportation

player.PlayerPawn.Value?.Teleport(position, angles, velocity);

Reading Velocity and Position

var velocity = player.PlayerPawn.Value?.AbsVelocity;
var position = player.PlayerPawn.Value?.AbsOrigin;
var angles = player.PlayerPawn.Value?.EyeAngles;

GameData & Function Hooking

SwiftlyS2 provides a powerful system for working with game signatures, offsets, and function hooking. GameData files are stored in each plugin's own resources/gamedata/ folder, allowing each plugin to manage its own signatures and offsets independently - unlike CounterStrikeSharp, which relies on a single shared gamedata.json.

This is an advanced topic. Most plugins won't need to use function hooking directly.

Before writing your own hook, check Core.GameHooks. It already exposes typed hooks for many functions CounterStrikeSharp plugins hook by hand: Entities (TakeDamage, Touch, AcceptInput, FireOutput, ...), Items (CanAcquire, GetItemInLoadout), Weapons (CanUse, Drop), Pawn, Controller (ProcessUsercmds) and a full set of Movement hooks.

Delegate Definition

In SwiftlyS2, you need to define delegates that match the native function signatures:

// CSS - no explicit delegate needed, uses DynamicHook
// Hook handlers receive DynamicHook for parameter extraction

Signature Lookup

var funcAddress = GameData.GetSignature("CCSPlayer_FindMatchingWeaponsForTeamLoadout");
var func = new MemoryFunctionVoid<IntPtr, string, int, bool, IntPtr>(funcAddress);
func.Invoke(player.PlayerPawn.Value.Handle, weaponName, (int)team, false, vectorPtr);

VTable Hooking

VirtualFunctions.GiveNamedItemFunc.Hook(OnGiveNamedItemPre, HookMode.Pre);
VirtualFunctions.GiveNamedItemFunc.Hook(OnGiveNamedItemPost, HookMode.Post);

Hook Handler Implementation

// CSS - separate Pre and Post handlers
private HookResult OnGiveNamedItemPre(DynamicHook hook)
{
    var itemServices = hook.GetParam<CCSPlayer_ItemServices>(0);
    string classname = hook.GetParam<string>(1);
    return HookResult.Continue;
}
 
private HookResult OnGiveNamedItemPost(DynamicHook hook)
{
    // Post-execution logic
    return HookResult.Continue;
}

Hook Cleanup

VirtualFunctions.GiveNamedItemFunc.Unhook(OnGiveNamedItemPre, HookMode.Pre);
VirtualFunctions.GiveNamedItemFunc.Unhook(OnGiveNamedItemPost, HookMode.Post);

Migration Tips & Best Practices

Start Small

Begin by migrating basic functionality first:

  1. Plugin structure and metadata
  2. Basic commands and events
  3. Player operations and messaging
  4. Configuration and database connections
  5. Advanced features like menus and function hooking

Common Migration Patterns

Pattern: Update Package References

Always update your .csproj file first:

<!-- Remove CSS references -->
<!-- <PackageReference Include="CounterStrikeSharp.API" Version="..." /> -->
 
<!-- Add SwiftlyS2 reference -->
<PackageReference Include="SwiftlyS2.CS2" Version="*-*" ExcludeAssets="runtime" PrivateAssets="all" />

Pattern: Core Access

Replace global utility classes with Core services:

// Old CSS pattern
Utilities.GetPlayers().ForEach(player => { });
 
// New SwiftlyS2 pattern
Core.PlayerManager.GetAllPlayers().ForEach(player => { });

Pattern: Event Registration

Use attributes for cleaner event handling:

// Instead of manual registration in Load()
// Core.GameEvent.HookPost<EventPlayerDeath>(OnPlayerDeath);
 
// Use attributes (recommended)
[GameEventHandler(HookMode.Post)]
private HookResult OnPlayerDeath(EventPlayerDeath @event) { return HookResult.Continue; }

Testing Your Migration

  1. Compile First: Ensure your plugin compiles without errors
  2. Test Basic Functions: Verify commands, events, and player operations work
  3. Check Resources: Ensure translations and config files are properly located
  4. Test Hot Reload: SwiftlyS2 has improved hot reload support

Getting Help

  • Documentation: Check the SwiftlyS2 API documentation for detailed reference
  • Examples: Look at the plugin template examples in the examples/ folder
  • Community: Join the SwiftlyS2 Discord or forums for community support

Migration from CounterStrikeSharp to SwiftlyS2 typically results in cleaner, more maintainable code with better performance and more features.