Back to API Reference
Class

UniTextBase

abstract
Implements:IPointerDownHandlerIPointerUpHandlerIPointerEnterHandlerIPointerExitHandlerIPointerMoveHandler

UniTextBase partial class implementing auto-size and layout computation.

Remarks

Shared between Canvas (UniText) and world-space (UniTextWorld) variants. Canvas integrates through ILayoutElement and ILayoutController so Unity's LayoutRebuilder drives the two phases; world-space has the render pipeline invoke EnsureLayoutFit directly. Two-phase design. The phases have independent caches because they key on different inputs and are driven by different UI rebuild points: EnsureLayoutComputed — the main pass. Computes the "preferred" state (cachedPreferredHeight and initial cachedEffectiveFontSize) at the unconstrained ideal font size. Cached by rect.width; independent of rect.height. Invoked from CalcLayoutInputVertical and returns what the parent layout group reads as "what this text wants". EnsureLayoutFit — the second pass. When auto-size is on and the actual rect.height is smaller than the preferred, shrinks cachedEffectiveFontSize to fit. Cached by rect.height. Deliberately does not update cachedPreferredHeight — "preferred" stays what the text wants, not what the rect gives it. Without this separation, shrinking preferred on one frame would make parents (e.g. ContentSizeFitter + VerticalLayoutGroup) assign an even smaller rect next frame, causing a feedback shrink loop.

Nested Types

public float PreferredHeight{ get }

Gets the computed preferred height for the current rect (accounts for auto-sizing).

public UniTextDirtyFlags CurrentDirtyFlags{ get }

Gets the current dirty flags indicating what needs rebuilding.

public TextProcessor TextProcessor{ get }

Gets the text processor instance handling shaping and layout.

public UniTextMeshGenerator MeshGenerator{ get }

Gets the mesh generator instance.

public UniTextFontProvider FontProvider{ get }

Gets the font provider managing font assets and fallbacks.

public UniTextBuffers Buffers{ get }

Gets the buffer container for text processing.

public ReadOnlyMemory<char> RawText{ get }

Gets the runtime source text — the last value assigned via Text or any SetText overload, before any resolver substitution. Zero-alloc. Backing is either a string or a char buffer supplied to SetText.

public ReadOnlyMemory<char> ResolvedText{ get }

Gets the substitute produced by the attached TextResolver on the last rebuild, or an empty memory when no resolver is attached or TryResolve returned. Zero-alloc. Test TextOverride for Resolver to know if this value is in use.

public ReadOnlyMemory<char> RenderedText{ get }

Gets the text actually fed into the parsing / shaping / layout pipeline: the resolver's output if one is active, otherwise RawText. Zero-alloc. Still contains markup; for the markup-stripped form use CleanText.

public ReadOnlySpan<char> CleanText{ get }

Gets RenderedText with parsed markup removed. Zero-alloc. The backing buffer is pooled and may be rewritten on the next parse — do not store the span; call new string(span) if you need a stable string.

public TextOverrideSource TextOverride{ get }

Combination of flags describing which runtime source(s) are currently overriding the serialized Text. Flags may combine — for example, SetText | Resolver when a SetText buffer feeds an attached resolver that further substitutes the text.

public IUniTextResolver TextResolver{ get; set }

Gets or sets a resolver that may override the source text before parsing without modifying the serialized text field. Useful for editor-time localization preview and runtime text-binding without dirtying scenes or prefabs. See IUniTextResolver for the contract.

public Vector2 ResultSize{ get }

Gets the computed size of the rendered text.

public ReadOnlySpan<PositionedGlyph> ResultGlyphs{ get }

Gets the positioned glyphs after processing.

public UniTextFont PrimaryFont{ get }

Gets the primary font from the font collection.

public float CurrentFontSize{ get }

Gets the current effective font size (accounts for auto-sizing).

public IReadOnlyList<Style> Styles{ get }

Gets the list of registered modifiers.

public IReadOnlyList<StylePreset> StylePresets{ get }

Gets the list of modifier configuration assets.

public bool UseGlobalStylePreset{ get; set }

When (default), GlobalStylePreset is applied to this component as an extra preset registered after the local StylePresets list. Disable to opt this component out of project-wide rules — local Styles and local StylePresets still apply. Toggling the value invalidates the parser so the next pipeline pass picks up the new effective preset set.

public string Text{ get; set }

Gets or sets the serialized source text. The getter returns the serialized field as-is and has no side effects — use RenderedText to observe what is actually being rendered when an override (SetText buffer or TextResolver) is active.

public TextHighlighter Highlighter{ get; set }

Gets or sets the text highlighter for visual feedback on interactions.

public UniTextFontStack FontStack{ get; set }

Gets or sets the font collection.

public float FontSize{ get; set }

Gets or sets the base font size in points.

public string Language{ get; set }

Gets or sets the default BCP 47 language tag for this text (e.g. zh-Hans, zh-Hant, ja, ko, en-US). Activates the OpenType locl feature and drives preferredLanguage font selection. Per-range overrides via <lang=...>...</lang> take priority.

public TextDirection BaseDirection{ get; set }

Gets or sets the base text direction (LTR, RTL, or Auto-detect).

public bool WordWrap{ get; set }

Gets or sets whether word wrapping is enabled.

public HorizontalAlignment HorizontalAlignment{ get; set }

Gets or sets the horizontal text alignment.

public VerticalAlignment VerticalAlignment{ get; set }

Gets or sets the vertical text alignment.

public TextOverEdge OverEdge{ get; set }

Gets or sets the top edge metric for text box trimming.

public TextUnderEdge UnderEdge{ get; set }

Gets or sets the bottom edge metric for text box trimming.

public LeadingDistribution LeadingDistribution{ get; set }

Gets or sets how extra leading from line-height is distributed.

public UniTextRenderMode RenderMode{ get; set }

Gets or sets the text rendering mode (SDF for rounded, MSDF for sharp corner effects).

public bool AutoSize{ get; set }

Gets or sets whether automatic font sizing is enabled.

public float MinFontSize{ get; set }

Gets or sets the minimum font size for auto-sizing.

public float MaxFontSize{ get; set }

Gets or sets the maximum font size for auto-sizing.

public Color color{ get; set }
public int GlyphCount{ get }

Gets the total number of glyphs.

public static bool UseParallel{ get; set }

Gets or sets whether parallel processing is enabled for multiple components.

public TextHitResult LastHoverResult{ get }

Gets the last hover hit test result.

public bool IsHoveringRange{ get }

Returns true if currently hovering over an interactive range.

public InteractiveRange CurrentHoverRange{ get }

Gets the interactive range currently being hovered, if any.

protected void EnsureLayoutComputed()

Main layout pass. Computes the "preferred" state — cachedPreferredHeight and an initial cachedEffectiveFontSize — for the current rect width. Cached by width only: result is independent of rect.height.

protected void EnsureLayoutFit()

Full layout: main pass then, if needed, shrinks cachedEffectiveFontSize under the current rect.height. Main-pass state comes from the width cache; second pass is cached by rect.height so repeat calls within a frame are free.

public bool HasModifier()

Returns true if any style on this component has a modifier of type T.

public bool HasModifier()

Returns true if any style on this component has a modifier assignable to modifierType.

public bool TryGetStyle()

Finds the first style whose modifier is of type T.

public bool TryGetStyle()

Finds the first style whose modifier is assignable to modifierType.

public bool TryGetWholeTextStyle()

Finds the first whole-text style (range..) whose modifier is of type T.

public bool TryGetWholeTextStyle()

Finds the first whole-text style whose modifier is assignable to modifierType.

public IEnumerable<Style> GetStylesOfType()

Enumerates every style whose modifier is of type T, local first.

public IEnumerable<Style> GetStylesOfType()

Enumerates every style whose modifier is assignable to modifierType, local first.

public void SetWholeText()

Adds or updates a whole-text style of modifier type T. If an existing local whole-text style exists, its parameter is updated in place; otherwise a new style is added via AddStyle.

public void SetWholeText()

Adds or updates a whole-text style for modifierType, creating a new modifier via factory when none is found locally.

public bool ClearWholeText()

Removes the first local whole-text style whose modifier is of type T. Returns true if a style was removed.

public bool ClearWholeText()

Removes the first local whole-text style whose modifier is assignable to modifierType.

public bool ToggleWholeText()

Inverts the presence of a whole-text style of type T. Adds the style with parameter when absent, removes it when present. Returns true if the style is present after the call.

public bool ToggleWholeText()

Inverts the presence of a whole-text style for modifierType, creating a new modifier via factory when adding.

public string GetWholeTextParameter()

Returns the parameter of the first whole-text style of type T, or null.

public string GetWholeTextParameter()

Returns the parameter of the first whole-text style of modifierType, or null.

protected override void OnDidApplyAnimationProperties()

Unity callback invoked after Animator writes animated properties into this component's serialized fields. Subclasses delegate to their composed AnimationHandlerBase<T> to diff the animated state and aggregate the resulting UniTextDirtyFlags in a single SetDirty call.

protected abstract void HandleAnimation()

Diffs animated fields against the cached baseline through the subclass's animation handler. Implementations should forward to their composed AnimationHandlerBase<T> instance.

public void SetText()

Sets text content from a char array without allocating a string. Ideal for frequently updated text (timers, scores, etc.).

public void SetText(ReadOnlyMemory<char> source)

Sets the text to render without writing to the serialized text field. The change is visible at runtime and in edit mode without marking the scene or prefab as dirty — suitable for editor-time preview (localization) or transient runtime substitution.

public void SetText(string source)

Sets the text to render without writing to the serialized text field. Convenience overload equivalent to SetText(source.AsMemory()). The change does not mark the scene or prefab as dirty.

public void SetDirty()

Marks the specified aspects of the text as needing rebuild.

public override void SetVerticesDirty()
public override void SetMaterialDirty()
public void AddStyle()

Adds a style to this component at runtime.

public bool RemoveStyle()

Removes a style from this component at runtime.

public void ClearStyles()

Removes all styles from this component.

public void AddRule(IParseRule rule)

Adds a standalone parse rule (one that operates without a modifier, e.g. <noparse>). The rule must report IsStandalone as.

public bool RemoveRule(IParseRule rule)

Removes a standalone rule previously added via AddRule.

public void AddStylePreset()

Adds a shared style preset to this component at runtime.

public bool RemoveStylePreset()

Removes a shared style preset from this component at runtime.

public void ClearStylePresets()

Removes all shared style presets from this component.

protected override void OnEnable()
protected virtual void Update()
protected override void OnDisable()
protected override void OnDestroy()
protected virtual void Sub()
protected virtual void UnSub()
protected void DeInit()
protected override void OnRectTransformDimensionsChange()
protected override void OnTransformParentChanged()
public override void Rebuild()
protected override void UpdateMaterial()
protected virtual bool ValidateAndInitialize()
protected abstract void UpdateRendering()

Applies generated mesh data to the rendering backend (CanvasRenderer or MeshRenderer sub-meshes).

protected abstract void ClearAllRenderers()

Clears all sub-mesh renderers (without destroying GameObjects).

protected virtual void OnSetDirty()

Called after SetDirty. Override to trigger Canvas layout rebuild.

protected virtual void OnDeInit()

Called during DeInit for subclass-specific cleanup (e.g., stencil materials).

public void CollectRangeEntries(int startCluster, int endCluster, PooledList<LineRangeEntry> output)

Collects per-line geometric runs of positioned glyphs whose clusters fall inside [startCluster, endCluster). Output bounds are in mesh-local coordinates with X clamped to each line's visible content extent (trailing whitespace excluded via width). One LineRangeEntry is emitted per contiguous run within a line — multiple entries per line are possible if the matched clusters are non-contiguous in visual order.

public void GetRangeBounds()

Gets bounding rectangles for a cluster range. One Rect per contiguous run of glyphs within a line that falls inside [startCluster, endCluster). Trailing whitespace at line ends is excluded (CSS Text §4.1.3). Empty wrapped lines whose break codepoint lies inside the range receive a synthetic narrow rect for caret/selection rendering.

protected virtual void PrepareForParallel()
protected void EnsureFirstPassComplete()

Ensures the first pass (parsing, BiDi, shaping) has run. No-op in the normal pipeline (Phase 1 already ran). Enables LayoutRebuilder.ForceRebuildLayoutImmediate to work outside the pipeline.

public void OnPointerDown()
public void OnPointerUp()
public void OnPointerClick()
public void OnPointerEnter()
public void OnPointerExit()
public void OnPointerMove()
public TextHitResult HitTest(Vector2 localPosition, float maxDistance)

Performs hit testing in local coordinates.

public TextHitResult HitTestScreen(Vector2 screenPosition, Camera eventCamera, float maxDistance)

Performs hit testing from screen coordinates.

protected abstract Camera ResolveEventCamera()

Resolves the camera to use for screen-to-local conversion based on the event source.

protected float cachedEffectiveFontSize

Cached effective font size after auto-sizing. Zero means layout has not been computed; consumers fall back to maxFontSize/fontSize as appropriate.

protected float cachedPreferredHeight

Cached preferred height — what the text wants at its unconstrained (main-pass) size. Not updated by the second pass: parent layout groups read this as "desired height", which must stay stable even when the rect is smaller than desired.

protected ReadOnlyMemory<char> sourceText
protected float fontSize
protected TextDirection baseDirection
protected bool wordWrap
protected TextOverEdge overEdge
protected TextUnderEdge underEdge
protected LeadingDistribution leadingDistribution
protected bool autoSize
protected float minFontSize
protected float maxFontSize
protected TextProcessor textProcessor
protected UniTextMeshGenerator meshGenerator
protected UniTextBuffers buffers
protected List<UniTextRenderData> renderData
public CachedTransformData cachedTransformData

Cached transform data captured before parallel processing.

public Action Animated

Raised after Unity Animator applies animated property values to this component, once the base field diff has issued the corresponding SetDirty. Modifiers with their own animatable fields should subscribe and run an equivalent diff over their state, calling SetDirty with the flags that match their effect.

public Action Rebuilding

Raised before text is rebuilt.

public Action BeforeGenerateMesh

Raised after glyph positioning but before mesh generation. Modifiers inject virtual PositionedGlyphs here.

public Action RectHeightChanged

Raised when the RectTransform height changes.

public Action<UniTextDirtyFlags> DirtyFlagsChanged

Raised when dirty flags change, indicating what needs rebuilding.

public static Action BeforeProcess

Raised before any text processing in the current canvas update cycle.

public static Action MeshApplied

Raised after meshes are applied to renderers, before canvas rendering begins.

public static Action AfterProcess

Raised after all text processing is complete, after MeshApplied.

public Action<TextHitResult> TextClicked

Raised when any text is clicked, providing hit test details.

public Action<InteractiveRangeHit> RangeClicked

Raised when an interactive range is clicked.

public Action<InteractiveRangeHit> RangeEntered

Raised when the pointer enters an interactive range (desktop only).

public Action<InteractiveRangeHit> RangeExited

Raised when the pointer exits an interactive range (desktop only).

public Action<TextHitResult> HoverChanged

Raised when hover position changes, providing hit test details (for InputField).

See Also