Skip to main content

Inspector controls

Guide

Replace one declarative field control with project-owned UI Toolkit, add Workbench validation, and reuse the same dropdown engine as the built-in authoring fields

Standard serialized fields and Runtime metadata cover most Workbench extensions. When one field needs project-specific interaction, register an Editor-only factory for that field instead of replacing the complete content Inspector. The remaining fields continue through the shared schema renderer, so the same derived object still works in Workbench and the normal Unity Inspector.

Custom control and validation code belongs in an Editor assembly. The derived content class and its serialized data remain in the runtime assembly described by Inspector extensions.

The complete split is available in Samples~/InspectorExtensions/. Copy the sample into project-owned folders before adapting it; do not edit the package copy as production code.

Reference the Editor assembliesโ€‹

Create an Editor-only Assembly Definition that references the project content assembly, GCS Editor, and Shared Editor:

{
"name": "YourGame.GCS.Content.Editor",
"references": [
"YourGame.GCS.Content",
"TinyGiants.GCS.Runtime",
"TinyGiants.GCS.Editor",
"TinyGiants.Shared.Editor"
],
"includePlatforms": [
"Editor"
]
}

This assembly is excluded from player builds. Runtime code must not reference GCSInspectorControlRegistry, GCSInspectorValidationRegistry, TGDropdown, or UI Toolkit Editor controls.

Register one field controlโ€‹

GCSInspectorControlRegistry matches a content type and serialized field name. Register during every Domain Reload with [InitializeOnLoad] or [InitializeOnLoadMethod].

using System.Collections.Generic;
using TinyGiants.GCS.Editor;
using TinyGiants.Shared.Editor;
using UnityEditor;
using UnityEngine.UIElements;

[InitializeOnLoad]
public static class SampleInspectorRegistrations
{
static SampleInspectorRegistrations()
{
GCSInspectorControlRegistry.Register<SampleCard>(
nameof(SampleCard.Element),
BuildElementControl);

GCSInspectorValidationRegistry.Register<SampleCard>(
"sample.card.rules",
ValidateCard);
}

private static VisualElement BuildElementControl(
GCSInspectorFieldContext context)
{
SerializedProperty property = context.GetProperty();
var field = GCSEditableSelectField.FromEntries(
property != null ? property.stringValue : string.Empty,
BuildElementEntries,
value => context.Modify(
"Edit Element",
current => current.stringValue = value ?? string.Empty));

context.RegisterRefresh(current =>
field.SetValueWithoutNotify(current.stringValue ?? string.Empty));

return field;
}

private static IList<TGDropdownEntry> BuildElementEntries()
{
return new List<TGDropdownEntry>
{
new TGDropdownEntry
{
Key = "fire",
Label = "Fire",
Payload = "fire",
Tooltip = "Fire-aligned rules"
},
new TGDropdownEntry
{
Key = "ice",
Label = "Ice",
Payload = "ice",
Tooltip = "Ice-aligned rules"
}
};
}

private static IEnumerable<GCSInspectorValidationResult> ValidateCard(
SampleCard card)
{
if (card.RequiredLevel < 0)
{
yield return new GCSInspectorValidationResult(
GCSInspectorValidationSeverity.Error,
"Required Level cannot be negative.",
fieldLabel: "Required Level",
category: "Sample",
propertyPath: nameof(SampleCard.RequiredLevel));
}
}
}

The registration replaces only SampleCard.Element. Base GameCard objects and unrelated derived types keep the declarative control. Registering the same content type and field name again replaces the earlier factory. When registrations exist for both a base type and a more specific derived type, the closest matching type wins.

Use the serialized field contextโ€‹

GCSInspectorFieldContext keeps the custom control inside the same serialized-data and Undo path as built-in controls.

MemberUse
TargetCurrent concrete ScriptableObject
SerializedObjectSerialized wrapper for the current target
PropertyPathExact path of the field being replaced
FieldReflected field metadata
LabelFinal displayed label after GCSLabel, InspectorName, or nicification
GetProperty()Updates the serialized object and resolves the current property
Modify(undoLabel, mutation)Applies a serialized change, records Undo, marks the target dirty, and refreshes Workbench
RegisterRefresh(refresh)Refreshes the control after Undo/Redo or an external serialized change
UseFullWidthMakes the returned element occupy the complete section width

Do not keep a SerializedProperty reference and assume it remains valid after an array edit, Undo, or Inspector rebuild. Resolve it through GetProperty() when the value is needed. Use RegisterRefresh with SetValueWithoutNotify so an Undo refresh does not create another edit callback.

Set UseFullWidth before returning a compound control:

private static VisualElement BuildTimelineControl(
GCSInspectorFieldContext context)
{
context.UseFullWidth = true;
var timeline = new VisualElement();
timeline.AddToClassList("sample-timeline");
return timeline;
}

The registry expects a UI Toolkit VisualElement. IMGUI-only controls need their own IMGUIContainer, including their own focus and serialized-change handling.

Reuse GCS field controls directlyโ€‹

Project factories can construct the same public controls used by the declarative renderer.

ControlPurpose
GCSSelectFieldSelection-only string field
GCSEditableSelectFieldEditable string plus option dropdown
GCSTagFieldComma-separated values plus multiple-selection dropdown
GCSChipMultiSelectFieldOrdered removable chips plus multiple-selection dropdown
GCSEnumDropdown<T>Enum picker using GCS dropdown presentation
GCSBuffDebuffPickerTwo-segment Boolean control with custom labels
GCSDescriptionFieldGCS description editor with token and semantic-reference support
GCSSubAssetFieldCompact or card-style selector for registered GCS content
GCSSubAssetListFieldSerialized list editor for GCS content references
GCSFlowGraphFieldFlowGraph button and static entry or enemy-intent summary
GCSDeckEntriesFieldGameDeck card count picker and summary

Prefer Runtime attributes when they already select the required control. A registry factory is appropriate when the field needs custom composition, conditional interaction, project-specific commands, or a value model that the declarative attributes do not express.

Add project validationโ€‹

GCSInspectorValidationRegistry runs project validators together with built-in Workbench validation. Register a stable ID so a Domain Reload or repeated initialization replaces the same validator instead of adding duplicates.

GCSInspectorValidationRegistry.Register<SampleEncounter>(
"sample.encounter.rewards",
encounter => ValidateRewards(encounter));

A validator returns zero or more GCSInspectorValidationResult values:

ValueResult in Workbench
WarningAdds a warning to the current database Issue Badge
ErrorAdds an error to the current database Issue Badge
CategoryDisplays the project-defined issue category
MessageAppears after the content object's display name
PropertyPathExact SerializedProperty.propertyPath used first to jump to and flash one Inspector row
FieldLabelDisplayed-label fallback when PropertyPath is empty or cannot be resolved

Use the five-parameter constructor (severity, message, fieldLabel, category, propertyPath) when an issue belongs to one serialized field. For a top-level field, pass nameof(SampleCard.RequiredLevel). For a nested field, pass its complete relative path such as Stats.RequiredLevel. Array and list paths must use Unity's exact serialized form, including segments such as Array.data[0].

Workbench resolves PropertyPath first. When the path is empty or no matching serialized property exists, it falls back to FieldLabel. FieldLabel is the displayed label, not necessarily the C# field name; use the value from [GCSLabel], then [InspectorName], or Unity's nicified field name. The existing four-parameter constructor (severity, message, fieldLabel, category) remains available and uses this label fallback. Leave both values empty when the issue applies to the complete asset.

Validation reports problems but does not repair data, prevent saving, or enforce a player-build invariant. Keep runtime invariants in runtime code. If a derived type overrides OnEnable or OnValidate, call the base implementation so GCS identity and base-type normalization continue to run.

Build entries for TGDropdownโ€‹

TGDropdown is the shared TinyGiants Editor popup behind GCS selection controls. Every entry separates identity, display, grouping, and returned data:

using System.Collections.Generic;
using TinyGiants.Shared.Editor;

private static List<TGDropdownEntry> BuildAbilityEntries()
{
return new List<TGDropdownEntry>
{
new TGDropdownEntry
{
Key = "fireball",
Label = "Fireball",
GroupPath = new List<string> { "Combat", "Magic", "Fire" },
Payload = "fireball",
Tooltip = "Deals fire damage",
Enabled = true
},
new TGDropdownEntry
{
Key = "guard-break",
Label = "Guard Break",
GroupPath = new List<string> { "Combat", "Physical" },
Payload = "guard-break",
Tooltip = "Reduces armor"
}
};
}
Entry memberMeaning
KeyUnique stable row identity for multiple-selection state
LabelVisible row text
GroupPathExplicit page path with any number of segments
PayloadObject returned to callbacks; equal payloads share one Multiple-mode selection state
TooltipOptional row tooltip
EnabledWhether the item can be selected

Group remains available for legacy slash-delimited paths such as Combat/Magic/Fire. New code should use GroupPath; its segments are explicit, so a slash inside one segment does not create another page. A null GroupPath falls back to Group, while an empty list explicitly places the entry on the root page. Search covers labels and complete display paths. GroupOrder supplies preferred child-page names at every level, with unspecified names sorted ordinally.

Assign every row a unique stable Key when Multiple mode represents persisted data. If a key is omitted or collides, the dropdown creates an internal identity that is unique only for that popup lifetime. Rows with equal payloads act as aliases in Multiple mode: selecting or clearing either row updates all rows that represent that payload and invokes the callback once.

Open a single-selection dropdownโ€‹

Single mode returns one payload and closes after a choice. When ShowNoneOption is enabled, choosing None calls OnPicked with null.

using System;
using TinyGiants.GCS.Editor;
using TinyGiants.Shared.Editor;
using UnityEngine.UIElements;

private static void OpenSingle(
Button anchor,
Action<string> commit)
{
TGDropdown.Open(new TGDropdownConfig
{
Title = "Ability",
AnchorRect = GCSVisualKit.ScreenRectOf(anchor),
Entries = BuildAbilityEntries(),
SelectionMode = TGDropdownSelectionMode.Single,
ShowNoneOption = true,
NoneLabel = "No Ability",
OnPicked = payload => commit(payload as string),
GroupOrder = new[] { "Combat", "Utility" },
MinWidth = 260f
});
}

When this callback edits an Inspector field, call context.Modify inside OnPicked rather than writing the target object directly.

Open a multiple-selection dropdownโ€‹

Multiple mode reads initial state through IsSelected and reports every toggle through OnSelectionChanged. The following wrapper commits one ordered list when the popup closes:

using System;
using System.Collections.Generic;
using TinyGiants.GCS.Editor;
using TinyGiants.Shared.Editor;
using UnityEngine.UIElements;

private static void OpenMultiple(
Button anchor,
IEnumerable<string> initial,
Action<List<string>> commit)
{
var selected = new List<string>();
if (initial != null)
{
foreach (string value in initial)
{
if (!string.IsNullOrEmpty(value) && !selected.Contains(value))
selected.Add(value);
}
}

TGDropdown.Open(new TGDropdownConfig
{
Title = "Granted Abilities",
AnchorRect = GCSVisualKit.ScreenRectOf(anchor),
Entries = BuildAbilityEntries(),
SelectionMode = TGDropdownSelectionMode.Multiple,
ShowNoneOption = false,
IsSelected = payload =>
payload is string id && selected.Contains(id),
OnSelectionChanged = (payload, isSelected) =>
{
if (!(payload is string id)) return;
if (isSelected && !selected.Contains(id)) selected.Add(id);
if (!isSelected) selected.Remove(id);
},
OnClose = () => commit(new List<string>(selected)),
SelectedItemsFirst = true,
ClearSearchOnSelection = true,
MaxHeight = 360f
});
}

For immediate persistence, call context.Modify from OnSelectionChanged. For a single Undo step, keep popup-local state as above and call context.Modify once from OnClose.

Open a count dropdownโ€‹

Count mode displays a non-negative count for every entry. Left-click reports +1; right-click reports -1.

using System;
using System.Collections.Generic;
using TinyGiants.GCS.Editor;
using TinyGiants.Shared.Editor;
using UnityEngine;
using UnityEngine.UIElements;

private static void OpenCounts(
Button anchor,
IDictionary<string, int> initial,
Action<Dictionary<string, int>> commit)
{
var counts = initial != null
? new Dictionary<string, int>(initial, StringComparer.Ordinal)
: new Dictionary<string, int>(StringComparer.Ordinal);

TGDropdown.Open(new TGDropdownConfig
{
Title = "Ability Copies",
AnchorRect = GCSVisualKit.ScreenRectOf(anchor),
Entries = BuildAbilityEntries(),
SelectionMode = TGDropdownSelectionMode.Count,
ShowNoneOption = false,
GetCount = payload =>
{
string id = payload as string;
return id != null && counts.TryGetValue(id, out int count)
? count
: 0;
},
OnCountChanged = (payload, delta) =>
{
if (!(payload is string id)) return;
counts.TryGetValue(id, out int current);
counts[id] = (int)Math.Max(0L, Math.Min(int.MaxValue, (long)current + delta));
},
OnClose = () =>
commit(new Dictionary<string, int>(counts, StringComparer.Ordinal)),
CountHint = "Left click +1 ยท Right click โˆ’1",
MaxHeight = 520f
});
}

Count mode keeps the popup open while values change. The callback receives only a signed delta, so the owner remains responsible for the stored count model and any maximum-count rule. OnCountChanged must update the backing model read by GetCount before the callback returns; the popup reads GetCount again immediately to display the committed value.

Configure popup behavior consistentlyโ€‹

TGDropdownConfig exposes the shared behavior without requiring another popup implementation.

SettingEffect
Title, AnchorRect, EntriesDefines the popup heading, screen anchor, and data
SelectionModeChooses Single, Multiple, or Count interaction
ShowNoneOption, NoneLabelConfigures the optional Single-mode null row
GroupOrderApplies preferred child-page order at every path level
Width, MinWidth, MaxHeightOverrides or constrains popup dimensions
SelectedItemsFirstMoves selected Multiple-mode entries before unselected entries on each page
ClearSearchOnSelectionClears search after a Multiple-mode toggle
CountHintReplaces the Count-mode instruction text
OnCloseRuns once for every popup close path

The popup owns interaction and temporary visual state, not project serialization. Keep the project value in the serialized field, refresh the control through RegisterRefresh, and commit through context.Modify.

Respect the extension boundaryโ€‹

  • Register controls and validation from an Editor assembly after every Domain Reload.

  • Keep serializable fields, option providers, and typed runtime access in a runtime assembly.

  • Use declarative attributes before replacing a field with a registry factory.

  • Use context.Modify for every persisted custom-control change and RegisterRefresh for Undo/Redo.

  • Keep validation side-effect free; it reports an issue but does not mutate the target.

  • Treat TGDropdown as an Editor authoring control, not a runtime game UI.

  • Do not expect an Inspector control registered through the project API to change Workbench List rows, Preview, card-face layout, or gameplay automatically.

These boundaries preserve the common serialized Inspector while allowing a project to replace only the interaction that genuinely needs custom UI.