ui
[UI Toolkit] Fix TextElement Font Scaling Anomalies
Solution
Unity 2021.3.x - Unity 6.3.x
Published Sat, Mar 7
When the scale of a FontAsset is modified during runtime, existing TextElement components do not automatically refresh to display the updated scaling. Standard methods like MarkDirtyRepaint() prove ineffective for propagating these specific changes because the internal uitkTextHandle remains in a cached state.
Quick-Fix
Modifying a FontAsset scale requires forcing an internal refresh of the uitkTextHandle via reflection to ensure the text mesh is properly rebuilt.
using System.Reflection;
using UnityEngine.UIElements;
public static class UIUtil
{
public static void MarkDirtyText(this TextElement textElement)
{
if (textElement == null) return;
// Access the internal versioning system of VisualElement
MethodInfo incrementVersion = typeof(VisualElement).GetMethod("IncrementVersion",
BindingFlags.NonPublic | BindingFlags.Instance);
// Notify both Repaint and Layout version changes
incrementVersion?.Invoke(textElement, new object[] { (long)(VersionChangeType.Repaint | VersionChangeType.Layout) });
// Access the internal handle property
PropertyInfo handleProperty = typeof(TextElement).GetProperty("uitkTextHandle",
BindingFlags.NonPublic | BindingFlags.Instance);
object uitkTextHandle = handleProperty?.GetValue(textElement);
if (uitkTextHandle != null)
{
// Force the specific text handle to mark itself as dirty
MethodInfo setDirty = uitkTextHandle.GetType().GetMethod("SetDirty",
BindingFlags.Public | BindingFlags.Instance);
setDirty?.Invoke(uitkTextHandle, null);
}
}
}
Related Posts Haven't quite found a solution to your problem? We think these posts might help you.
[Canvas System] Duplicated UI Assets: Awake Initialization Skip[UI Toolkit] Fix Keyboard/Gamepad Button Interaction on Submit[UI Toolkit] Master Percentage Binding for Responsive Layouts
Content inspired by a Unity discussion post.