Skip to main content

VisualElement Extensions

UI Toolkit interfaces in one call chain — no separate line per property and style.

Quick start​

Before — Unity APIAfter — FastTools
var title = new Label("Ability Config");
title.style.fontSize = 14;

var header = new VisualElement();
header.style.paddingLeft = 12;
header.style.paddingRight = 12;
header.style.paddingTop = 10;
header.style.paddingBottom = 10;
header.Add(title);
var header = new VisualElement()
.SetPaddingX(12)
.SetPaddingY(10)
.AddChild(new Label("Ability Config")
.SetFontSize(14));

Configuration methods return the original element, preserving its type. All extensions except the Editor extensions also work in a player build.

Element properties​

UnityFastTools
tooltip = "Mana cost"SetTooltip("Mana cost")
isDelayed = trueSetDelayed(true)
bindItem = BindRowSetBindItem(BindRow)
text = "Ability Config"SetTextSelf("Ability Config")
SetEnabled(false)SetEnabledSelf(false)

The suffix Self marks a name that Unity uses, or may start to use, for a method that returns void. Such a method takes precedence over an extension, so a chain through it does not compile; the FastTools method returns the element instead.

On Unity 6000.6 and later, SetTextSelf has more overloads. They set the text through Unity's allocation-free TextElement.SetText, so text that changes every frame needs no ToString():

fps.SetTextSelf(frameCount); // int, long or ulong
speed.SetTextSelf(velocity, "0.0"); // float with an optional format
title.SetTextSelf(characters); // ReadOnlySpan<char>
log.SetTextSelf(builder); // StringBuilder
log.SetTextSelf(buffer, start, length); // a slice of a char[]

While the element is not attached to a panel, they set a string instead: it allocates, and Unity logs no warning. A bare null does not compile on 6000.6; cast it: SetTextSelf((string)null).

The full list of extensions is in the API reference.

note

VisualElementExtensions and INotifyValueChangedExtensions have the same names as classes of UnityEngine.UIElements. Extension calls are not affected; a call through the class name needs the namespace: Aspid.FastTools.UIElements.VisualElementExtensions.SetName(title, "Title").

Children​

UnityFastTools
Add(title)AddChild(title)
Insert(0, title)InsertChild(0, title)
Remove(title)RemoveChild(title)
RemoveAt(0)RemoveChildAt(0)
Clear()ClearChildren()

These methods return the parent. For multiple elements, use AddChildren, InsertChildren, RemoveChildren.

Before — Unity APIAfter — FastTools
if (isFree)
body.Add(helpBox);
body.AddChildIf(isFree, helpBox);

All of these methods have a variant with the suffix If.

Styles​

every side

Other style methods follow the same pattern. See the API reference for the full list.

Colors from strings and assets from Resources​

Before — Unity APIAfter — FastTools
if (ColorUtility.TryParseHtmlString(
"#FFC24D", out var color))
badge.style.color = color;
badge.SetColor("#FFC24D");
var texture = Resources
.Load<Texture2D>("UI/Card");
if (texture != null)
root.style.backgroundImage = texture;
root.SetBackgroundImageFromResources(
"UI/Card");

SetImage, SetSprite, SetVectorImage and the style sheet methods also have a …FromResources variant.

SetBackgroundImage also takes a Sprite or a VectorImage: icon.SetBackgroundImage(sprite). To clear the background, pass StyleKeyword.None; a bare null does not compile.

Bold and italic​

Adding or removing one style preserves the other.

CallEffect
AddBoldUnityFontStyleAndWeight()Adds bold
RemoveBoldUnityFontStyleAndWeight()Removes bold
AddItalicUnityFontStyleAndWeight()Adds italic
RemoveItalicUnityFontStyleAndWeight()Removes italic
SetNormalUnityFontStyleAndWeight()Removes both styles
note

The presets read the current value from the element's style, not the resolved style: a weight set in USS counts as Normal.

Custom USS properties​

Before — Unity APIAfter — FastTools
if (evt.customStyle.TryGetValue(
ThemeProperty, out var raw)
&& Enum.TryParse(raw,
ignoreCase: true,
out PreviewTheme theme))
ApplyTheme(theme);
if (evt.customStyle.TryGetByEnum(
ThemeProperty,
out PreviewTheme theme))
ApplyTheme(theme);

USS classes and style sheets​

UnityFastTools
AddToClassList("selected")AddClass("selected")
RemoveFromClassList("selected")RemoveClass("selected")
ToggleInClassList("selected")ToggleClass("selected")
EnableInClassList("selected", isFree)EnableClass("selected", isFree)
ClearClassList()ClearClasses()
styleSheets.Add(sheet)AddStyleSheet(sheet)
styleSheets.Insert(0, sheet)InsertStyleSheet(0, sheet)
styleSheets.Remove(sheet)RemoveStyleSheet(sheet)
styleSheets.Clear()ClearStyleSheets()
  • Methods for several classes or style sheets take the plural name: AddClasses("selected", "free"), AddStyleSheets(baseSheet, themeSheet).
  • EnableClasses takes the flag first: EnableClasses(isFree, "selected", "free").
  • EnableStyleSheet(darkSheet, isDark) adds or removes a style sheet, as EnableClass does for a class.

All of these methods have a variant with the suffix If. Name the arguments when a method takes two flags: EnableClassIf(condition: isEditable, "selected", enable: isFree).

Values and events​

UnityFastTools
value = 10SetValue(10)
SetValueWithoutNotify(10)SetValue(10, notify: false)
RegisterValueChangedCallback(OnChanged)AddValueChanged(OnChanged)
UnregisterValueChangedCallback(OnChanged)RemoveValueChanged(OnChanged)
clicked += RefreshAddClicked(Refresh)
clicked -= RefreshRemoveClicked(Refresh)

For custom value types, use the generic SetValue<T, TValue>(…) and AddValueChanged<TField, TValue>(…).

For Unity.Mathematics types (float3, int2, quaternion), SetValue and AddValueChanged need no type arguments. The overloads are in the separate assembly Aspid.FastTools.VisualElements.Math (API reference), which compiles when the com.unity.mathematics package is installed, and on Unity 6000.5 and later, where Unity.Mathematics ships in the engine.

Unity's methods for event callbacks return void, so their FastTools counterparts have the suffix Self:

UnityFastTools
RegisterCallback<ClickEvent>(OnClick)RegisterCallbackSelf<Button, ClickEvent>(OnClick)
RegisterCallbackOnce<ClickEvent>(OnClick)RegisterCallbackOnceSelf<Button, ClickEvent>(OnClick)
UnregisterCallback<ClickEvent>(OnClick)UnregisterCallbackSelf<Button, ClickEvent>(OnClick)

These methods take the same TrickleDown and user arguments as Unity's and return the element, so a chain continues:

var apply = new Button()
.RegisterCallbackSelf((PointerEnterEvent evt) => Hover())
.SetTooltip("Apply");

The type arguments are inferred only from a callback with a typed parameter, as above. For a method group or a lambda without parameter types, name both: RegisterCallbackSelf<Button, ClickEvent>(OnClick).

Focus​

UnityFastTools
Focus()FocusSelf()
Blur()BlurSelf()
Before — Unity APIAfter — FastTools
if (manaCost.focusController?
.focusedElement == manaCost)
Refresh();
if (manaCost.IsFocused())
Refresh();
note

IsFocused() returns false for a field inside another field (a FloatField of a Vector3Field) or in a list row. Track such a field with FocusInEvent and FocusOutEvent.

Manipulators​

Before — Unity APIAfter — FastTools
title.AddManipulator(
new Clickable(Refresh));
title.AddClickable(Refresh);

For keyboard navigation and context menus:

title.AddKeyboardNavigationManipulator(OnNavigate);
title.AddContextualMenuManipulator(BuildMenu);

The out overload lets you keep the manipulator for removal:

title.AddClickable(Refresh, out var clickable);

// Later
title.RemoveManipulatorSelf(clickable);

Editor extensions​

Before — Unity APIAfter — FastTools
manaCost.bindingPath = "_manaCost";
manaCost.Bind(serializedObject);
manaCost.BindTo(
serializedObject, "_manaCost");
UnityFastTools
bindingPath = "_manaCost"SetBindingPath("_manaCost")
BindProperty(property)BindPropertyTo(property)
Unbind()UnbindFrom()

PropertyField gets SetLabel and AddValueChanged / RemoveValueChanged with a SerializedPropertyChangeEvent:

var manaCost = new PropertyField(
serializedObject.FindProperty("_manaCost"))
.SetLabel("Mana cost")
.AddValueChanged(_ => Refresh());

Open the script on double-click​

AddOpenScriptCommand opens the script of a MonoBehaviour or ScriptableObject in the IDE on a left double-click; for any other object it adds nothing:

title.AddOpenScriptCommand(target);

The element's window​

var window = title.GetOwnerWindow();

Returns the element’s window. If none is found, falls back to the focused window, then the window under the pointer; returns null if none is available.

The FastTools theme​

rootVisualElement
.AddAspidWindowTheme()
.AddStyleSheet(catalogSheet);

The window takes the colours of the FastTools windows: the theme picked under Appearance in the FastTools settings, a theme of the project included, and the light palette on the light editor skin. A new pick recolours it at once. Colour your own style sheet with the --aspid-colors-* tokens:

.ability-sidebar {
background-color: var(--aspid-colors-surface-card);
}

Package sample​

The catalog window of the EditorTools sample is built with these extensions.

The Ability Catalog window from the EditorTools sampleThe Ability Catalog window from the EditorTools sample