Extendable in-game developer debug console and Editor command runner for Unity 6. It combines a pure-C# command registry, quoted argument tokenization, strongly typed and attribute-discovered commands, bounded command history, an IMGUI runtime overlay bound to Unity's Input System, and a UI Toolkit Editor window.
- Three command registration paths:
- Reflection discovery via
IDebugCommandProviderimplementations. [DebugCommand]attribute on static methods (auto-discovered) or instance methods (bound viaDebugCommandRegistry.RegisterAttributedMethods).- Runtime programmatic registration via
DebugController.RegisterCommand(...)andDebugController.UnregisterCommand(...).
- Reflection discovery via
- Multiple command shapes: Supports parameterless
DebugCommand, rawDynamicDebugCommand(string[]), strongly typedDebugCommand<T1>andDebugCommand<T1, T2>, and reflected[DebugCommand]methods with default parameters (string,int,float,double,bool, and case-insensitive enums). - Quoted argument tokenizer (
CommandTokenizer): Splits command lines on whitespace while preserving spaces inside single or double quotes (say "hello world" 'single quoted') and handling escaped quotes and backslashes (\",\',\\). - Autocomplete and bounded history (
CommandHistory): Prefix-prioritized, alphabetically sorted command suggestions (Tabto cycle) plusUp/Downarrow navigation over a configurable ring buffer with consecutive duplicate suppression. - Scrollable console log and built-in commands: Captures echoed input, validation errors, and command output in a bounded buffer (
maxOutputLines), with built-inhelp(HelpCommand) andclear(ClearCommand) providers plusOutputLinesandOutputChangedAPIs. - Unity 6 fast Play Mode compatibility: Resets static state on
RuntimeInitializeLoadType.SubsystemRegistration(safe without Domain Reload) and clones assignedInputActionAssetinstances at runtime so asset state is never mutated. - UI Toolkit Editor tooling: Includes Debug Console Window (
Tools > HaruChanZ64 > Analysis > DebugCommandSystem > Debug Console Window) with a searchable command catalog, clickable suggestion chips, and Edit Mode / live Play Mode execution, plus one-click scene setup menus (Tools > HaruChanZ64 > Analysis > DebugCommandSystem > Add DebugController to SceneandGameObject > DebugCommandSystem > DebugController).
- Unity
6000.0or newer com.unity.inputsystem(1.11.2+) with Edit > Project Settings > Player > Active Input Handling set to Input System Package (New) or Both
- Open Window > Package Manager in Unity 6 (
6000.0+). - Click + (top-left) and choose Install package from git URL....
- Enter:
https://github.com/haruchanz64/DebugCommandSystem.git
Add the package path to Packages/manifest.json:
{
"dependencies": {
"com.haruchanz64.debugcommandsystem": "file:../Plugins/DebugCommandSystem"
}
}- Confirm Active Input Handling under Edit > Project Settings > Player is set to Input System Package (New) or Both.
- Add a controller to your scene using Tools > HaruChanZ64 > Analysis > DebugCommandSystem > Add DebugController to Scene (or GameObject > DebugCommandSystem > DebugController, or drag
Prefabs/DebugController.prefabinto the Hierarchy). Both menu items select an existing sceneDebugControllerrather than creating duplicates. - Open Tools > HaruChanZ64 > Analysis > DebugCommandSystem > Debug Console Window to browse discovered commands and execute them in Edit Mode or Play Mode.
- Enter Play Mode and press
F1to toggle the in-game console overlay:- Type a command and press
Enter(orNumpad Enter) to execute. - Press
Tabto cycle autocomplete suggestions. - Press
Up/Downarrows to navigate command history. - Run
helpto print all registered commands orclearto clear the output buffer.
- Type a command and press
Every submitted line flows through four stages inside DebugCommandRegistry.Execute(string):
- Tokenization (
CommandTokenizer.Tokenize): Splits the raw line on unquoted whitespace while preserving quoted strings ("...",'...') and unescaping\",\', and\\inside quotes. - Case-insensitive lookup: Matches
tokens[0]against the registry dictionary (StringComparer.OrdinalIgnoreCase). Unknown IDs returnCommandExecutionStatus.UnknownCommand. - Argument parsing and dispatch (
DebugCommandBase.TryExecute): Passestokens[1..]to the matched command. Typed commands and reflected[DebugCommand]methods convert tokens usingCommandArgumentParser.TryConvertwithCultureInfo.InvariantCulture(acceptingtrue/false/1/0forbooland case-insensitive names for enums). Missing or unparseable arguments returnCommandExecutionStatus.InvalidArgumentswith a usage message. - Exception wrapping: Unhandled exceptions (unwrapping
TargetInvocationException) are caught into aCommandExecutionResultwithCommandExecutionStatus.Exceptionso a faulty command does not crash the console loop.
On Start(), DebugController scans all non-system assemblies in AppDomain.CurrentDomain via DebugCommandRegistry.DiscoverFromAssemblies, registering concrete IDebugCommandProvider classes and static methods decorated with [DebugCommand]. Any commands registered earlier via DebugController.RegisterCommand(...) are preserved and re-applied on top (overwriteExisting: true).
DebugController persists across scenes via DontDestroyOnLoad, clones its assigned InputActionAsset (or falls back to InputSystem.actions), and binds the Console action map (Toggle, Execute, AutoComplete).
Static methods in any non-system assembly are discovered automatically on startup. Default parameter values become optional arguments:
using HaruChanZ64.DebugCommandSystem.Commands;
using HaruChanZ64.DebugCommandSystem.Core;
using UnityEngine;
public static class GameplayCheats
{
public enum Difficulty { Easy, Normal, Hard }
[DebugCommand("grant_gold", "Grants gold to the player", "grant_gold <amount> [reason]")]
public static void GrantGold(int amount, string reason = "debug")
{
DebugController.Instance?.LogOutput($"Granted {amount} gold ({reason}).");
}
[DebugCommand("set_difficulty", "Changes active difficulty")]
public static void SetDifficulty(Difficulty mode)
{
Debug.Log($"Difficulty set to {mode}");
}
}Use IDebugCommandProvider for self-contained command classes discovered automatically without static state:
using HaruChanZ64.DebugCommandSystem.Commands;
using HaruChanZ64.DebugCommandSystem.Interfaces;
using UnityEngine;
public sealed class SpawnEnemyCommand : IDebugCommandProvider
{
public DebugCommandBase GetCommand()
{
return new DebugCommand<string, int>(
"spawn_enemy",
"Spawns N enemies by ID",
"spawn_enemy <enemyId> <count>",
(enemyId, count) => Debug.Log($"Spawned {count}x {enemyId}")
);
}
}Register temporary commands at runtime, or bind instance [DebugCommand] methods to a live component and clean them up on disable:
using HaruChanZ64.DebugCommandSystem.Commands;
using HaruChanZ64.DebugCommandSystem.Core;
using UnityEngine;
public sealed class PlayerDebugBindings : MonoBehaviour
{
private void OnEnable()
{
DebugController.RegisterCommand(new DebugCommand(
"fps_cap",
"Sets target frame rate to 60",
"fps_cap",
() => Application.targetFrameRate = 60));
if (DebugController.Instance != null)
{
DebugController.Instance.Registry.RegisterAttributedMethods(GetType(), this);
}
}
private void OnDisable()
{
DebugController.UnregisterCommand("fps_cap");
DebugController.UnregisterCommand("tp");
}
[DebugCommand("tp", "Teleports this object to XYZ coordinates")]
private void Teleport(float x, float y, float z)
{
transform.position = new Vector3(x, y, z);
}
}Override DebugCommandBase.TryExecute when you need custom argument types, validation rules, or variable-length parsing beyond CommandArgumentParser:
using HaruChanZ64.DebugCommandSystem.Commands;
using UnityEngine;
public sealed class SetColorCommand : DebugCommandBase
{
public SetColorCommand()
: base("set_tint", "Applies a hex color tint", "set_tint <#RRGGBB>")
{
}
public override bool TryExecute(string[] args, out string error)
{
if (args == null || args.Length != 1 || !ColorUtility.TryParseHtmlString(args[0], out var color))
{
error = $"Expected hex color. Usage: {commandFormat}";
return false;
}
Debug.Log($"Applied color {color}");
error = null;
return true;
}
}| Type | Namespace | Purpose | Built-in implementation |
|---|---|---|---|
IDebugCommandProvider |
HaruChanZ64.DebugCommandSystem.Interfaces |
Reflection-discovered provider supplying a DebugCommandBase |
HelpCommand, ClearCommand |
DebugCommandBase |
HaruChanZ64.DebugCommandSystem.Commands |
Abstract base class for executable commands (TryExecute) |
DebugCommand, DynamicDebugCommand, DebugCommand<T1>, DebugCommand<T1, T2> |
DebugCommandAttribute |
HaruChanZ64.DebugCommandSystem.Commands |
Marks static or instance methods for reflected command registration | [DebugCommand] |
CommandArgumentParser |
HaruChanZ64.DebugCommandSystem.Commands |
Invariant-culture string-to-value converter (string, int, float, double, bool, enums) |
CommandArgumentParser |
DebugCommandRegistry |
HaruChanZ64.DebugCommandSystem.Core |
Pure-C# command store, assembly discovery, autocomplete, and execution dispatcher | DebugCommandRegistry |
CommandTokenizer |
HaruChanZ64.DebugCommandSystem.Core |
Splits command lines with single/double quote and backslash escape support | CommandTokenizer |
CommandHistory |
HaruChanZ64.DebugCommandSystem.Core |
Bounded ring buffer with consecutive deduplication and Up/Down cursor navigation | CommandHistory |
DebugController |
HaruChanZ64.DebugCommandSystem.Core |
Persistent MonoBehaviour hosting the in-game IMGUI console, Input System bindings, and output buffer | DebugController |
DebugConsoleWindow |
HaruChanZ64.DebugCommandSystem.Editor |
UI Toolkit Editor window for browsing, filtering, autocompleting, and running commands | DebugConsoleWindow |
DebugControllerSceneUtility |
HaruChanZ64.DebugCommandSystem.Editor |
Scene setup menus and EnsureDebugControllerInScene() deduplication helper |
DebugControllerSceneUtility |
Import Custom Commands Sample (Samples~/CustomCommands) from the Package Manager Samples tab:
SampleGodModeCommand: registers a parameterlessgod_modecommand viaIDebugCommandProviderandDebugCommandthat toggles an internal flag.SampleGiveItemCommand: registers a parameterizedgive_item <itemId> [count]command viaIDebugCommandProviderandDynamicDebugCommandwith optional count parsing.
The package includes EditMode NUnit tests under Tests/Editor/ runnable from Window > General > Test Runner (EditMode tab):
Tests/Editor/CommandTokenizerAndHistoryTests.cs: verifies whitespace and empty input handling, single/double quoted tokens with backslash escapes, andCommandHistorynavigation, consecutive duplicate suppression, and capacity eviction.Tests/Editor/DebugCommandRegistryTests.cs: verifies case-insensitive dispatch across parameterless, dynamic, and typed (int,enum,bool) commands,[DebugCommand]default parameters and missing-argument errors, prefix-before-substring autocomplete ordering, andUnregister.Tests/Editor/DebugConsoleEditorTests.cs: verifiesDebugControllerSceneUtility.EnsureDebugControllerInScene()creates a single controller and reuses existing instances, andDebugController.LogOutput/ClearOutputupdateOutputLinesand raiseOutputChanged.
DebugControllerdisables itself on startup with an Input System error: Under Edit > Project Settings > Player > Active Input Handling, select Input System Package (New) or Both.DebugControllercompiles its input bindings behind#if ENABLE_INPUT_SYSTEM.- Custom
InputActionAssetfails to initialize: If you replace the defaultDebugInputActionsasset or rely on project-wideInputSystem.actions, the asset must define aConsoleaction map containingToggle,Execute, andAutoCompleteactions. - Instance
[DebugCommand]methods do not appear automatically: Automatic assembly scanning only instantiatesIDebugCommandProviderclasses (requiring a public parameterless constructor) and registersstatic[DebugCommand]methods. For instance methods, callDebugController.Instance.Registry.RegisterAttributedMethods(target.GetType(), target)manually and unregister them when destroyed. - Commands in custom assemblies are not discovered:
DiscoverFromAssembliesskips assemblies whose names begin withSystem,mscorlib,netstandard,Microsoft.,Mono.,UnityEngine,UnityEditor,Unity., ornunit.. Avoid those prefixes on game assemblies containing commands. - Unsupported parameter types on typed or attributed commands:
CommandArgumentParserhandlesstring,int,float,double,bool(true/false/1/0), and enums. ForVector3, colors, or custom types, useDynamicDebugCommand, avoid(string[])attributed method, or a customDebugCommandBasesubclass. - Edit Mode commands in
DebugConsoleWindowvs. Play Mode: Outside Play Mode,DebugConsoleWindowruns commands against an Editor-discovered registry and keeps a local 200-line output buffer (handlinghelpandclearlocally). Commands that depend onDebugController.Instanceor Play Mode scene state require Play Mode with aDebugControllerin the scene.