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

Menus (Deprecated)

SwiftlyS2 menus provide an interactive, per-player UI layer for settings, selections, and action flows, through Core.MenusAPI (APIIMenuManagerAPI).

The classic menu API is deprecated: every interface, event args class and enum in SwiftlyS2.Shared.Menus, and Core.MenusAPI itself, is marked [Obsolete] and will be removed in a future version. Use Core.Menu (APIIMenuService) for new plugins - see Menu System.

  1. Create a builder with Core.MenusAPI.CreateBuilder().
  2. Configure behavior (sound, freeze, auto-close, keybind overrides) and appearance (builder.Design).
  3. Add options and call Build().
  4. Open and close through Core.MenusAPI.

The manager members below cover the whole lifecycle:

MemberDescription
APIIMenuManagerAPI.CreateBuilderCreates a new APIIMenuBuilderAPI.
APIIMenuManagerAPI.CreateMenuBuilds a menu directly from APIMenuConfiguration/APIMenuKeybindOverrides objects.
APIIMenuManagerAPI.OpenMenuForPlayerOpens a menu for one player, closing any menu they already have open.
APIIMenuManagerAPI.OpenMenuOpens a menu for every player.
APIIMenuManagerAPI.CloseMenuForPlayerCloses a specific menu for one player; no effect if the player does not have it open.
APIIMenuManagerAPI.CloseActiveMenuCloses whatever menu the player currently has open.
APIIMenuManagerAPI.CloseMenuCloses a menu for every player who has it open.
APIIMenuManagerAPI.CloseAllMenusCloses every open menu for every player.
APIIMenuManagerAPI.GetCurrentMenuReturns the player's active menu, or null if they have none open.

APIIMenuManagerAPI.Core is the APIISwiftlyCore instance the manager belongs to, and APIIMenuManagerAPI.Configuration exposes the resolved core menu settings as a APIMenuManagerConfiguration:

MemberDescription
NavigationPrefix (string)Prefix used for menu navigation commands.
InputMode (string)Input mode that determines how player input is captured for menu navigation.
ButtonsUse / ButtonsScroll / ButtonsScrollBack / ButtonsExit (string)Default button mappings for selecting, scrolling down, scrolling up and closing.
SoundUseName / SoundScrollName / SoundExitName (string)Sound played when selecting, scrolling or exiting.
SoundUseVolume / SoundScrollVolume / SoundExitVolume (float)Volume of the corresponding sound (0.0 to 1.0).
ItemsPerPage (int)Maximum items per page. Menus exceeding this limit are paginated.

All of these come from Menu in configs/core.jsonc - see Core Configuration.

Builder Configuration

Every call under .Design returns back to the builder, so chain .Design. again for each design call:

var menu = Core.MenusAPI.CreateBuilder()
    .EnableSound()
    .SetPlayerFrozen(false)
    .SetAutoCloseDelay(0f)
    .SetSelectButton(KeyBind.E | KeyBind.Mouse1) // KeyBind is a [Flags] enum
    .SetMoveForwardButton(KeyBind.W)
    .SetMoveBackwardButton(KeyBind.S)
    .SetExitButton(KeyBind.Esc)
    .AddExtraButton(KeyBind.R, "Reset", (p, m) =>
    {
        p.SendChat("Reset action executed.");
    })
    .Design.SetMenuTitle("Gameplay Settings")
    .Design.SetMenuTitleItemCountVisible(true)
    .Design.SetMenuFooterVisible(true)
    .Design.SetCommentVisible(true)
    .Design.SetDefaultComment("Use W/S to move and E to select")
    .Design.SetMaxVisibleItems(5)
    .Design.SetGlobalScrollStyle(MenuOptionScrollStyle.WaitingCenter)
    .Build();
 
Core.MenusAPI.OpenMenuForPlayer(player, menu);

MaxVisibleItems only accepts [1, 5] or -1 (falls back to ItemsPerPage in configs/core.jsonc, see Core Configuration) - out-of-range values log an error and reset to -1.

Every APIIMenuBuilderAPI method returns the builder for chaining, except APIIMenuBuilderAPI.Build:

MethodDescription
APIIMenuBuilderAPI.Design (IMenuDesignAPI)The design interface of this menu, see Menu Design.
APIIMenuBuilderAPI.BindToParent(IMenuAPI parent)Binds the menu to a parent menu, so closing it returns to that menu.
APIIMenuBuilderAPI.AddOption(IMenuOption option)Adds an option to the menu.
APIIMenuBuilderAPI.EnableSound / APIIMenuBuilderAPI.DisableSoundTurns interaction sounds on or off.
APIIMenuBuilderAPI.EnableExit / APIIMenuBuilderAPI.DisableExitTurns the exit button for this menu on or off.
APIIMenuBuilderAPI.SetPlayerFrozen(bool frozen = false)Freezes player movement while the menu is open.
APIIMenuBuilderAPI.SetAutoCloseDelay(float seconds = 0f)Closes the menu automatically after the given number of seconds; 0 disables auto-close.
APIIMenuBuilderAPI.SetSelectButton / APIIMenuBuilderAPI.SetMoveForwardButton / APIIMenuBuilderAPI.SetMoveBackwardButton / APIIMenuBuilderAPI.SetExitButton (KeyBind)Overrides one navigation key bind of this menu. Combine keys with |.
APIIMenuBuilderAPI.AddExtraButton(KeyBind keyBind, string label, Action<IPlayer, IMenuAPI> action)Adds a custom button that is shown in the menu footer and runs action when pressed.
APIIMenuBuilderAPI.BuildBuilds and returns the finished APIIMenuAPI.

The Set*Button overrides replace the corresponding default from Menu.Buttons in configs/core.jsonc; a key bind that is not overridden keeps its default.

builder.Design (APIIMenuDesignAPI) controls appearance. Like the builder, every call returns the builder:

MethodDescription
APIIMenuDesignAPI.SetMenuTitle(string? title = null)Title displayed at the top of the menu; null clears it.
APIIMenuDesignAPI.SetMenuTitleVisible(bool visible = true)Shows or hides the title.
APIIMenuDesignAPI.SetMenuTitleItemCountVisible(bool visible = true)Shows or hides the item count in the title.
APIIMenuDesignAPI.SetMenuFooterVisible(bool visible = true)Shows or hides the footer.
APIIMenuDesignAPI.SetCommentVisible(bool visible = true)Shows or hides option comments.
APIIMenuDesignAPI.SetDefaultComment(string comment)Comment used for options that do not set their own.
APIIMenuDesignAPI.SetMaxVisibleItems(int count = 5)Maximum number of options visible at once. Valid range is [1, 5]; menus with more options are paginated.
APIIMenuDesignAPI.EnableAutoAdjustVisibleItems / APIIMenuDesignAPI.DisableAutoAdjustVisibleItemsTurns automatic adjustment of the visible item count on or off. When enabled, hiding the title or footer increases the effective visible count during rendering, without changing the SetMaxVisibleItems value.
APIIMenuDesignAPI.SetGlobalScrollStyle(MenuOptionScrollStyle style)Default scroll style for all options; individual options can override it.
SetNavigationMarkerColor / SetMenuFooterColor / SetVisualGuideLineColor / SetDisabledColorSets the color of navigation markers, the footer, the visual guide lines or disabled options. Each takes an overload for a hex string (null resets to the default), a Natives.Color, or a System.Drawing.Color.

APIMenuOptionScrollStyle is LinearScroll, APIMenuOptionScrollStyle.CenterFixed or APIMenuOptionScrollStyle.WaitingCenter.

Hex colors accept "#RGB", "#RGBA", "#RRGGBB" and "#RRGGBBAA"; an invalid value logs an error and the color resets to the default.

Key Binds

APIKeyBind is a [Flags] uint enum, so several keys can be combined with |:

Mouse1, Mouse2, Space, Ctrl, W, A, S, D, E, Esc, R, Alt, Shift, Weapon1, Weapon2, Grenade1, Grenade2, Tab, F.

In WASD input mode (Menu.InputMode in configs/core.jsonc), key bind overrides do not take effect.

Option Types

Built-in options live under SwiftlyS2.Core.Menus.OptionsBase:

var slider = new SliderMenuOption(
    text: "Round Time",
    min: 60f,
    max: 300f,
    defaultValue: 120f,
    step: 30f,
    totalBars: 8
);
 
slider.ValueChanged += (sender, args) =>
{
    args.Player.SendChat($"Round time: {args.NewValue:0}s");
};
 
var menu = Core.MenusAPI.CreateBuilder()
    .Design.SetMenuTitle("Player Preferences")
    .AddOption(slider)
    .Build();

The other value-holding options (APIToggleMenuOption, APIInputMenuOption, APIChoiceMenuOption, APISelectorMenuOption`1) follow the same constructor-plus-ValueChanged-handler pattern, just with their own value type (bool, string, etc. - see APIMenuOptionValueChangedEventArgs`1.OldValue/APIMenuOptionValueChangedEventArgs`1.NewValue).

Provide a pre-built submenu, or build it lazily when selected.

var advancedMenu = Core.MenusAPI.CreateBuilder()
    .Design.SetMenuTitle("Advanced")
    .AddOption(new ButtonMenuOption("Do advanced action"))
    .Build();
 
var openAdvanced = new SubmenuMenuOption("Advanced", advancedMenu);
 
var lazyAdvanced = new SubmenuMenuOption("Lazy Advanced", () =>
{
    return Core.MenusAPI.CreateBuilder()
        .Design.SetMenuTitle("Loaded On Demand")
        .AddOption(new TextMenuOption("This submenu was built on click"))
        .Build();
});

Open and Close Menus

Core.MenusAPI.OpenMenuForPlayer(player, menu);
Core.MenusAPI.CloseActiveMenu(player);
 
Core.MenusAPI.OpenMenu(menu);
Core.MenusAPI.CloseMenu(menu);
 
Core.MenusAPI.CloseAllMenus();
 
var current = Core.MenusAPI.GetCurrentMenu(player);

Both open methods have an overload taking a callback that runs when the menu is closed for that player:

Core.MenusAPI.OpenMenuForPlayer(player, menu, (p, m) => p.SendChat("Menu closed."));
Core.MenusAPI.OpenMenu(menu, (p, m) => p.SendChat("Menu closed for a player."));

APIIMenuAPI.ShowForPlayer/ APIIMenuAPI.HideForPlayer only affect visual display - prefer the manager methods above for full state handling and events.

MemberDescription
APIIMenuAPI.MenuManagerThe APIIMenuManagerAPI this menu belongs to.
APIIMenuAPI.ConfigurationThe APIMenuConfiguration of this menu.
APIIMenuAPI.KeybindOverridesThe APIMenuKeybindOverrides of this menu.
APIIMenuAPI.OptionScrollStyleThe APIMenuOptionScrollStyle of this menu.
APIIMenuAPI.BuilderThe builder this menu came from, if it was created with CreateBuilder.
APIIMenuAPI.TagFree-form object for your own bookkeeping.
APIIMenuAPI.Parent(IMenuAPI? ParentMenu, IMenuOption? TriggerOption) - the parent menu, and the option that opened this submenu.
APIIMenuAPI.OptionsRead-only list of the options in this menu.
APIIMenuAPI.AddOption / APIIMenuAPI.RemoveOptionAdds an option at runtime, or removes one - RemoveOption returns false if the option was not found.
APIIMenuAPI.MoveToOption / APIIMenuAPI.MoveToOptionIndexMoves a player's selection to an option (or an index), returning false if it does not exist.
APIIMenuAPI.GetCurrentOption / APIIMenuAPI.GetCurrentOptionIndexReads a player's highlighted option, or null/-1 if nothing is selected.

Like APIIMenuOption, APIIMenuAPI implements IDisposable.

Events

Global manager events

public override void Load(bool hotReload)
{
    Core.MenusAPI.MenuOpened += OnMenuOpened;
    Core.MenusAPI.MenuClosed += OnMenuClosed;
}
 
public override void Unload()
{
    Core.MenusAPI.MenuOpened -= OnMenuOpened;
    Core.MenusAPI.MenuClosed -= OnMenuClosed;
}
 
private void OnMenuOpened(object? sender, MenuManagerEventArgs args)
{
    if (args.Player != null)
        Core.Logger.LogInformation("Menu opened for {SteamId}", args.Player.SteamID);
}
 
private void OnMenuClosed(object? sender, MenuManagerEventArgs args) { /* same shape */ }

Both handlers receive APIMenuManagerEventArgs (Player, Menu).

Per-menu and per-option events

var adminOnly = new ButtonMenuOption("Admin Action");
 
adminOnly.Validating += (sender, args) =>
{
    // args.Player, args.Option are also available here
    if (!Core.Permission.PlayerHasPermission(args.Player.SteamID, "admin"))
    {
        args.Cancel = true;
        args.CancelReason = "You are not an admin.";
    }
};
 
adminOnly.Click += (sender, args) =>
{
    args.Player.SendChat("Admin action executed.");
    return ValueTask.CompletedTask;
};
 
adminOnly.BeforeFormat += (sender, args) => args.CustomText = $"[SECURE] {args.Option.Text}";
adminOnly.AfterFormat += (sender, args) => args.CustomText = $"<font color='#FFD700'>{args.CustomText}</font>";
 
var menu = Core.MenusAPI.CreateBuilder().Design.SetMenuTitle("Admin").AddOption(adminOnly).Build();
 
menu.OptionHovering += (sender, args) => { /* fired every render frame while hovering */ };
menu.OptionHovered += (sender, args) => { /* fired only when the hovered option changes */ };
menu.OptionSelected += (sender, args) => { /* fired when a selection is activated */ };
EventEvent args and notes
APIIMenuOption.ValidatingAPIMenuOptionValidatingEventArgs (Player, Option, settable Cancel and CancelReason). Runs before Click.
APIIMenuOption.ClickAPIMenuOptionClickEventArgs (Player, plus a read-only CloseMenu flag). Asynchronous - return ValueTask.CompletedTask.
APIIMenuOption.BeforeFormat / APIIMenuOption.AfterFormatAPIMenuOptionFormattingEventArgs (Player, Option, settable CustomText).
APIIMenuOption.VisibilityChanged / APIIMenuOption.EnabledChanged / APIIMenuOption.TextChangedAPIMenuOptionEventArgs; Player is null because these are global property changes.
APIIMenuAPI.OptionHoveringAPIMenuEventArgs (Player, Options). Fired once per render frame while an option is hovered - keep the handler cheap.
APIIMenuAPI.OptionHoveredAPIMenuEventArgs (Player, Options). Fired only when the hovered option changes.
APIIMenuAPI.OptionSelectedAPIMenuEventArgs (Player, Options). Fired when a selection is activated.

Click is declared as APIAsyncEventHandler`1 - ValueTask (object? sender, MenuOptionClickEventArgs args) - the async counterpart of EventHandler<T> that the other events use.

Runtime Updates

var option = new ButtonMenuOption("Dynamic Option");
var menu = Core.MenusAPI.CreateBuilder().AddOption(option).Build();
 
menu.AddOption(new TextMenuOption("Added later"));
menu.MoveToOptionIndex(player, 0);
 
option.SetVisible(player, false);
option.SetEnabled(player, false);

APIIMenuOption.Visible/ APIIMenuOption.Enabled are the global states; SetVisible/SetEnabled(player, ...) set per-player values on top of them. Per-player values have lower priority than the global property, so a globally hidden or disabled option stays hidden or disabled for every player.

Other APIIMenuOption members you can use while a menu is open:

MemberDescription
APIIMenuOption.Text / APIIMenuOption.CommentDisplayed text and comment. Global - changing them affects what all players see.
APIIMenuOption.Visible / APIIMenuOption.EnabledGlobal visibility and interaction state.
APIIMenuOption.SetVisible / APIIMenuOption.GetVisiblePer-player visibility.
APIIMenuOption.SetEnabled / APIIMenuOption.GetEnabledPer-player enabled state.
APIIMenuOption.TagFree-form object for your own bookkeeping.
APIIMenuOption.LineCountNumber of lines the option occupies (read-only).
APIIMenuOption.MaxWidthMaximum display width of the option text, in relative units.
APIIMenuOption.TextSizeAPIMenuOptionTextSize: ExtraSmall, Small, SmallMedium, Medium, MediumLarge, Large, ExtraLarge.
APIIMenuOption.TextStyleAPIMenuOptionTextStyle: TruncateEnd, TruncateBothEnds, ScrollLeftFade, ScrollRightFade, ScrollLeftLoop, ScrollRightLoop.
APIIMenuOption.PlaySoundWhether selecting this option plays the selection sound.
APIIMenuOption.CloseAfterClickWhether the menu closes after the option is clicked (read-only).
APIIMenuOption.MenuThe menu the option belongs to, or null until it is added to one.

For custom option implementations, APIIMenuOption also exposes

APIIMenuOption.GetDisplayText

(player, displayLine = 0), APIIMenuOption.IsClickTaskCompleted (player), APIIMenuOption.OnValidatingAsync (player, returns ValueTask<bool>) and APIIMenuOption.OnClickAsync (player, returns ValueTask).

Direct CreateMenu Usage

APIIMenuManagerAPI.CreateMenu is a lower-level alternative to the builder, taking explicit APIMenuConfiguration/ APIMenuKeybindOverrides objects (the same settings the builder's .Design/Set*Button calls configure) instead of a fluent chain:

var menu = Core.MenusAPI.CreateMenu(
    new MenuConfiguration { Title = "Raw Menu", MaxVisibleItems = 5 },
    new MenuKeybindOverrides { Select = KeyBind.E, Move = KeyBind.W, MoveBack = KeyBind.S, Exit = KeyBind.Esc },
    parent: null,
    optionScrollStyle: MenuOptionScrollStyle.CenterFixed,
    optionTextStyle: MenuOptionTextStyle.TruncateEnd
);

parent defaults to null, optionScrollStyle to

APIMenuOptionScrollStyle.CenterFixed and optionTextStyle to APIMenuOptionTextStyle.TruncateEnd.

MemberDefaultDescription
Title (string)"Menu"Title displayed at the top.
HideTitle / HideTitleItemCount / HideFooter / HideComment (bool)falseHides the title, the item count in the title, the footer or the comments.
PlaySound (bool)trueWhether interaction sounds play.
MaxVisibleItems (int)-1Options visible at once. Valid range [1, 5]; out-of-range values log an error and reset to -1, which falls back to ItemsPerPage.
AutoIncreaseVisibleItems (bool)trueWhether hiding the title or footer increases the effective visible item count during rendering.
FreezePlayer (bool)falseWhether player movement is frozen while the menu is open.
DisableExit (bool)falseWhether the exit button is disabled for this menu.
AutoCloseAfter (float)0fSeconds before the menu closes automatically; 0 or less disables auto-close.
NavigationMarkerColor / FooterColor / VisualGuideLineColor / DisabledColor (string?)nullHex colors for navigation markers, footer, visual guide lines and disabled options.
DefaultComment (string)""Comment used for options that do not set their own.
ExtraButtons (List<MenuExtraButton>)emptyExtra footer buttons, see APIMenuExtraButton (KeyBind, Label, Action).

All four members are KeyBind? and default to null, which keeps the core default from Menu.Buttons:

MemberDescription
SelectKey bind for activating the selection.
MoveKey bind for moving forward.
MoveBackKey bind for moving backward.
ExitKey bind for closing the menu.

Common Pitfalls

  • Open and close menus through Core.MenusAPI manager methods, not only ShowForPlayer/HideForPlayer.
  • Keep heavy logic out of OptionHovering - it runs every render frame while hovering.
  • Unsubscribe manager-level events (MenuOpened/MenuClosed) during plugin Unload().