Skip to content

Game.ToolSystem

Assembly:
Namespace: Game.Tools

Type: class

Base: GameSystemBase, IPreDeserialize

Summary:
ToolSystem is the central manager for runtime tool behaviour in Cities: Skylines 2. It coordinates the active tool (placement/selection/etc.), prefab-based tool activation, infoviews and infomodes (visual overlays with colors/parameters), input barriers for blocking UI/mouse actions, and raises events when tools, prefabs or infoviews change. It also integrates with the game's update pipeline (via UpdateSystem) to run tool updates and manage shader globals used to draw infoview overlays. This system is useful to modders who need to interact with or extend the tool/infoview pipeline, toggle infomodes, or respond to tool changes.


Fields

  • protected const string kToolKeyGroup = "tool"
    Description: Key group name used by the input mapping for tool actions.

  • protected const string kToolCancelKeyGroup = "tool cancel"
    Description: Key group name used for tool-cancel actions.

  • protected const string kToolApplyKeyAction = "tool apply"
    Description: Action name used to apply tool actions in input mappings.

  • protected const string kToolCancelKeyAction = "tool cancel"
    Description: Action name used to cancel tool actions in input mappings.

  • public Action<ToolBaseSystem> EventToolChanged
    Description: Event invoked when the active tool changes. Subscribers receive the new ToolBaseSystem (can be null).

  • public Action<PrefabBase> EventPrefabChanged
    Description: Event invoked when the active prefab changes on the active tool.

  • public Action<InfoviewPrefab> EventInfoviewChanged
    Description: Event invoked when the active infoview is changed.

  • public Action EventInfomodesChanged
    Description: Event invoked when the set of active infomodes changes.

  • private ToolBaseSystem m_ActiveTool
    Description: The currently active tool instance.

  • private Entity m_Selected
    Description: Entity currently selected by the tool system.

  • private ToolBaseSystem m_LastTool
    Description: The tool that was active during the last update (used to detect tool switches and ensure proper enabling/disabling).

  • private InfoviewPrefab m_CurrentInfoview
    Description: Currently active InfoviewPrefab used to show infomode overlays.

  • private InfoviewPrefab m_LastToolInfoview
    Description: Infoview used by the last tool — used to detect infoview changes between tools.

  • private PrefabSystem m_PrefabSystem
    Description: Cached reference to the game's PrefabSystem for prefab/entity lookups.

  • private UpdateSystem m_UpdateSystem
    Description: Cached reference to the game's UpdateSystem used to perform update phases.

  • private ToolRaycastSystem m_ToolRaycastSystem
    Description: Cached reference to the system performing tool raycasts.

  • private DefaultToolSystem m_DefaultToolSystem
    Description: The fallback/default tool system instance used when no tool-specific prefab is active.

  • private List<ToolBaseSystem> m_Tools
    Description: Lazily-initialized list of registered tools.

  • private List<InfomodePrefab> m_LastToolInfomodes
    Description: Cached list of infomodes that the last tool requested; used to compare and update active infomodes.

  • private Dictionary<InfoviewPrefab, List<InfomodeInfo>> m_InfomodeMap
    Description: Cache mapping InfoviewPrefabs to their resolved list of InfomodeInfo objects (so buffer parsing is done once).

  • private Vector4[] m_InfomodeColors
    Description: Global array of colors passed to shaders for infoview rendering (managed groups of colors).

  • private Vector4[] m_InfomodeParams
    Description: Global array of parameter vectors (steps, speed, tiling, fill) for infomode shaders.

  • private int[] m_InfomodeCounts
    Description: Counters used to track how many infomodes are active per color group.

  • private NativeList<Entity> m_Infomodes
    Description: NativeList holding active Infomode entities. Allocated with Allocator.Persistent; must be disposed in OnDestroy.

  • private float m_InfoviewTimer
    Description: Timer used to animate infoview overlays; updated every ToolUpdate.

  • private bool m_FullUpdateRequired
    Description: Internal flag set during updates to request a full update on next safe point.

  • private bool m_InfoviewUpdateRequired
    Description: Flag indicating infoview shader arrays need recomputing.

  • private bool m_IsUpdating
    Description: True while the tool update is running; used to decide whether to set m_FullUpdateRequired vs fullUpdateRequired.

  • private InputBarrier m_ToolActionBarrier
    Description: InputBarrier used to block tool-related input actions when appropriate (e.g., game not in a playable mode).

  • private Dictionary<ProxyAction, InputBarrier> m_MouseToolBarriers
    Description: Per-mouse-action barriers used to block mouse actions when the cursor is over UI in KeyboardAndMouse scheme.

Properties

  • public Unity.Jobs.JobHandle producerHandle { get; private set }
    Note: This property does not exist in this class (template placeholder). (No producerHandle in ToolSystem)

  • public ToolBaseSystem activeTool { get; set; }
    Description: Gets or sets the current active tool. Setting invokes EventToolChanged and requests a full update when the tool changes. Setter ensures RequireFullUpdate() and event invocation.

  • public Entity selected { get; set; }
    Description: Currently selected Entity managed by the tool system.

  • public int selectedIndex { get; set; }
    Description: Public integer for tracking a selected index (usage depends on tools).

  • [CanBeNull] public PrefabBase activePrefab
    Description: Convenience accessor that returns the Prefab currently bound to the active tool (if any) by calling m_ActiveTool.GetPrefab(); may be null.

  • public InfoviewPrefab infoview { get; set; }
    Description: Setting this will call SetInfoview(value, null) if the value changes. Getter returns the current infoview field.

  • public InfoviewPrefab activeInfoview { get; }
    Description: Returns the current m_CurrentInfoview if it exists and is valid; otherwise returns null.

  • public GameMode actionMode { get; private set; } = GameMode.Other
    Description: Mode describing the context in which the ToolSystem is running (set in OnGamePreload).

  • public ApplyMode applyMode { get; }
    Description: Returns the apply mode from the last tool (m_LastTool.applyMode) or ApplyMode.None if there is no last tool.

  • public bool ignoreErrors { get; set; }
    Description: Public flag that tools may use to ignore/allow errors (settable by external code).

  • public bool fullUpdateRequired { get; private set; }
    Description: Public flag indicating a full update is required (set via RequireFullUpdate).

  • public List<ToolBaseSystem> tools { get; }
    Description: Lazily-initialized list of registered tools. Accessing ensures the list exists.

Constructors

  • public ToolSystem()
    Description: Default constructor. The system is initialized and marked with [Preserve] on OnCreate; most heavy initialization happens in OnCreate.

Methods

  • protected override void OnGamePreload(Purpose purpose, GameMode mode)
    Description: Called during game preload. Sets actionMode to the provided GameMode. Useful to detect Editor vs Game contexts.

  • [Preserve] protected override void OnCreate()
    Description: Initializes system references (PrefabSystem, UpdateSystem, ToolRaycastSystem, DefaultToolSystem), sets the default active tool, allocates internal structures (infomode arrays, NativeList), sets up input barriers for tools and mouse-tool interactions, hooks InputManager events (control scheme and mouse-over-UI changes), and initializes the shader global "colossal_InfoviewOn" to 0. This method is the main initialization point for runtime behaviour.

  • protected override void OnGameLoaded(Context serializationContext)
    Description: Called after game load (serialized state). Clears any active infomodes, nulls current infoview and ensures the Infoview shader global is turned off.

  • [Preserve] protected override void OnDestroy()
    Description: Disposes persistent NativeList m_Infomodes and InputBarrier m_ToolActionBarrier, disposes mouse tool barriers, resets shader global, and performs base cleanup. Always called to prevent native memory leaks.

  • [Preserve] protected override void OnUpdate()
    Description: Main per-frame update entry for the system. Updates the m_ToolActionBarrier.blocked state depending on game mode/loading state, sets m_IsUpdating, runs UpdateSystem phases PreTool and PostTool around ToolUpdate(), flushes the fullUpdateRequired flag, and clears m_IsUpdating.

  • public bool ActivatePrefabTool([CanBeNull] PrefabBase prefab)
    Description: Attempts to find a ToolBaseSystem in tools that accepts/sets the provided prefab via TrySetPrefab(prefab). If found, sets activeTool to that tool and returns true. If prefab is null or no tool accepts it, sets activeTool to the DefaultToolSystem and returns false. Useful for programmatically activating placement tools for a given prefab.

  • private void RefreshInputBarrier(Game.Input.InputManager.ControlScheme activeControlScheme, bool mouseOverUI)
    Description: Recomputes whether mouse-tool barriers should be blocked and updates each mouse action's InputBarrier.blocked state accordingly while respecting actions that are currently in progress.

  • private bool ShouldBlockBarrier(Game.Input.InputManager.ControlScheme activeControlScheme, bool mouseOverUI)
    Description: Returns true when the active control scheme is KeyboardAndMouse and the mouse is over UI (used to decide if mouse tool input should be blocked).

  • public void RequireFullUpdate()
    Description: Request a full update. If called while the system is updating (m_IsUpdating == true) it sets m_FullUpdateRequired which will be applied after the update; otherwise it sets the publicly visible fullUpdateRequired immediately.

  • private void ToolUpdate()
    Description: Core logic executed during OnUpdate. Manages infoview timer, tool enable/disable transitions, invokes UpdateSystem.ToolUpdate phase, tracks and synchronizes infoviews/infomodes between the active tool and current infoview, updates shader arrays when necessary, and ensures global shader time is set. This method contains the logic comparing m_LastTool and activeTool, calling tool enable/disable and updating infomode active states to reflect tool requests.

  • private void SetInfoview(InfoviewPrefab value, List<InfomodePrefab> infomodes)
    Description: Replace the current infoview with the provided one. Clears existing infomodes, then activates infomodes required by the new infoview (respecting supplemental/optional flags and current actionMode). Adds activated infomode entities to m_Infomodes, resets the infoview timer, flags shader update and invokes EventInfoviewChanged.

  • private void ClearInfomodes()
    Description: Clears all active infomodes by zeroing counters, removing the InfomodeActive component from every entity in m_Infomodes (via EntityManager.RemoveComponent), and clearing the native list. Prepares the system for a fresh set of active infomodes.

  • private void UpdateInfoviewColors()
    Description: Recomputes m_InfomodeColors and m_InfomodeParams arrays based on currently active infomodes. Reads InfomodePrefab color/parameter data and the InfomodeActive component to pack shader arrays, fills unused slots with defaults, sets shader globals ("colossal_InfoviewOn", "colossal_InfomodeColors", "colossal_InfomodeParams"). If no active infoview, turns off the "colossal_InfoviewOn" flag.

  • [CanBeNull] public List<InfomodeInfo> GetInfomodes(InfoviewPrefab infoview)
    Description: Returns a cached list of InfomodeInfo for the given InfoviewPrefab. If not cached, reads the DynamicBuffer from PrefabSystem, constructs InfomodeInfo objects (resolving InfomodePrefab instances), sorts them by priority, caches and returns the list.

  • public List<InfomodeInfo> GetInfoviewInfomodes()
    Description: Convenience method returning GetInfomodes(activeInfoview).

  • public bool IsInfomodeActive(InfomodePrefab prefab)
    Description: Returns true if the given InfomodePrefab's entity currently has an InfomodeActive component.

  • public void SetInfomodeActive(InfomodePrefab prefab, bool active, int priority)
    Description: Convenience overload — resolves the prefab to Entity via PrefabSystem.GetEntity and calls SetInfomodeActive(Entity, bool, int).

  • public void SetInfomodeActive(Entity entity, bool active, int priority)
    Description: Activates or deactivates the infomode described by the entity. Activation ensures color-group constraints (conflicting modes get deactivated) and calls Activate to add the InfomodeActive component. Deactivation removes InfomodeActive and updates internal lists and counters. When changes occur the method sets m_InfoviewUpdateRequired and invokes EventInfomodesChanged.

  • private void Activate(Entity entity, InfomodePrefab prefab, int priority)
    Description: Adds an InfomodeActive component to the entity, computing primary and optional secondary indices based on color groups and incrementing counters. Assigns the component with priority and indices.

  • private void Deactivate(Entity entity, InfomodePrefab prefab, InfomodeActive infomodeActive)
    Description: Removes an InfomodeActive component from an infomode entity. Adjusts color-group counts by calling Deactivate(colorGroup, index) for the primary and (if present) secondary indices, then removes the component from the entity.

  • private void Deactivate(int colorGroup, int activeIndex)
    Description: Internal helper to compact indices when an infomode of a given color group is deactivated. Shifts indices for remaining active items to maintain contiguous indices per color group and updates InfomodeActive components accordingly.

  • public void PreDeserialize(Context context)
    Description: Called prior to deserialization (part of IPreDeserialize). Clears infomodes and ensures the active tool is reset to the default tool system to maintain consistent state during load.

Usage Example

// Example: subscribe to tool changes and activate a prefab tool.
[Preserve]
protected override void OnCreate()
{
    base.OnCreate();
    // Get the system (this code runs inside another managed system)
    var toolSystem = World.GetOrCreateSystemManaged<Game.Tools.ToolSystem>();

    // Listen for when the active tool changes
    toolSystem.EventToolChanged += tool =>
    {
        Debug.Log($"Active tool changed to: {tool?.GetType().Name ?? "null"}");
    };

    // Activate a placement tool for a prefab (prefab obtained from PrefabSystem)
    var prefabSystem = World.GetOrCreateSystemManaged<PrefabSystem>();
    var buildingPrefab = prefabSystem.FindPrefab<PrefabBase>("MyBuildingPrefab");
    if (buildingPrefab != null)
    {
        bool activated = toolSystem.ActivatePrefabTool(buildingPrefab);
        Debug.Log($"ActivatePrefabTool returned: {activated}");
    }
}

Notes and Modding Tips: - The system manages native memory (NativeList m_Infomodes) — do not attempt to re-create/manage it externally; rely on provided APIs and events. - Infoview and infomode visuals depend on shader global arrays: "colossal_InfoviewOn", "colossal_InfoviewTime", "colossal_InfomodeColors", and "colossal_InfomodeParams". Use SetInfomodeActive / SetInfoview to modify shown overlays rather than setting shader globals directly. - Use ActivatePrefabTool to switch tools to those that expose TrySetPrefab, otherwise the DefaultToolSystem will be used. - Input is coordinated via InputBarrier objects; the system blocks mouse tool input when the mouse is over UI in keyboard-and-mouse mode. If you need to customize input handling, be mindful of the InputBarrier semantics and in-progress actions.