Docsv2.12.12
Back to API Reference
Class

UniTextBase

abstract
Implements:IPointerDownHandlerIPointerUpHandlerIPointerEnterHandlerIPointerExitHandlerIPointerMoveHandler

Shared base for UniText components — handles text processing (Unicode, BiDi, shaping, line breaking, modifiers, emoji, font fallback, variable fonts). Concrete subclasses supply the rendering backend: UniText (Canvas) and UniTextWorld (world-space).

Derived Types(2)

Types that inherit from UniTextBase.

Nested Types

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 }

The runtime source text — the last value assigned via Text or any SetText overload, before any resolver substitution. Zero-alloc.

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 effective primary font: the explicit Font if set, otherwise PrimaryFont from FontStack.

public float CurrentFontSize{ get }

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

public IReadOnlyList<Style> Styles{ get }

Local styles (modifier + parse rule pairs) registered on this component.

public IReadOnlyList<StylePreset> StylePresets{ get }

Shared StylePreset assets applied in addition to local Styles.

public bool UseGlobalStylePreset{ get; set }

Apply the project-wide GlobalStylePreset on top of local Styles and StylePresets. Disable to opt this component out of project-wide rules; local styles are unaffected.

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 UniTextFont Font{ get; set }

Optional explicit primary font. When set, overrides the primary picked from FontStack; the families in FontStack still serve as fallback for characters this font doesn't have.

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 }

BCP 47 language tag for this text (e.g. zh-Hans, ja, en-US). Picks the correct font variant for the script and enables the OpenType locl feature. Per-range overrides via <lang=...>...</lang> take priority.

public bool WordWrap{ get; set }

Gets or sets whether word wrapping is enabled.

public Vector4 Padding{ get; set }

Inner inset between the RectTransform edge and the text layout area. Components: x = Left, y = Bottom, z = Right, w = Top (same convention as raycastPadding). Increasing a side shrinks the text area on that side; the hit-test/raycast area is not affected.

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 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 RectTransform RenderRoot{ get }

Transform under which this component parents its generated render children (glyph sub-meshes, inline media). Main thread only — the Canvas backend lazily creates a hidden container.

public bool IsVisible{ get; set }

Whether the text is currently drawn and hit-testable. Setting this is equivalent to calling Show () or Hide ().

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.

public float PreferredHeight{ get }

Height the text content needs inside the padded inner rect (accounts for auto-sizing). Does not include vertical Padding — this is the content-box height, matching CSS height with box-sizing: content-box. The ILayoutElement contract adds vertical padding so ContentSizeFitter sizes the outer RectTransform to fit content + padding.

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 SetText(StringBuilder source)

Sets the text to render from a StringBuilder without writing to the serialized text field and without allocating a string. The contents are copied into a pooled internal buffer, so the supplied StringBuilder may be mutated freely after the call.

public void SetText(ReadOnlySpan<char> source)

Sets the text to render from a character span without writing to the serialized text field and without allocating a string. The span is copied into a pooled internal buffer, so its backing storage may be reused or released immediately after the call — making this the safe bridge from a pool-rented builder.

public Rect GetPaddedRect()

The rect with Padding applied: origin shifted by (Left, Bottom), size shrunk by (Left+Right, Bottom+Top), clamped to non-negative. Main-thread only.

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 abstract void ApplyVisibility()

Applies the current visibility (IsVisible) to the rendering backend. Must only toggle drawing — cull for Canvas, batch membership for world — never tear down or rebuild, so that Show/Hide stay allocation-free.

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 Show()

Re-shows text previously hidden with Hide. Reuses the already-built layout and mesh, so it is allocation-free and instant — no re-parse, shaping, layout or mesh rebuild. No-op if already visible.

public void Hide()

Hides the text while keeping its built layout, mesh and pooled buffers intact: stops drawing and pointer hit-testing without tearing down the pipeline. Prefer this over disabling the GameObject/component or assigning empty text for text shown and hidden repeatedly (pooled lists, tooltips, HUD) — those force a full pipeline rebuild on every re-show, whereas Show after Hide is free. No-op if already hidden.

public override bool Raycast()
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 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 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 T GetModifier()

Returns the first modifier of type T, or if none. Unlike the style queries above, also searches CompositeModifier children.

public bool TryGetModifier()

Same lookup as GetModifier<T> in the try-get pattern: when a modifier of type T was found.

public bool TryGetModifier()

Same lookup as GetModifier<T>, also returning the Style that owns the found modifier (for a match inside a CompositeModifier — the composite's style).

public int GetModifiers()

Collects every modifier of type T into results (cleared first) and returns the count. Same search scope as GetModifier<T>.

public static bool IsWholeTextStyle()

True when the style targets the entire text — either it has no rule (the canonical no-constraint form created by WholeText) or it carries a RangeRule whose single entry resolves to the full range.

public static bool IsWholeTextRule()

True only for a RangeRule instance that covers the full text. Use IsWholeTextStyle when checking a style — that variant also accepts the canonical rule-less form.

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.

public Vector2 MeasureText()

Measures the size text occupies under the given constraints and setting overrides — the displayed text, layout and mesh are left untouched.

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.

protected ReadOnlyMemory<char> sourceText
protected float fontSize
protected bool wordWrap
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.

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.

public Action Rebuilding

Raised before text is rebuilt.

public Action BeforeGenerateMesh

Raised after glyph positioning, before mesh generation. Last chance to inspect or inject positioned glyphs (used by per-glyph modifiers).

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 the hovered glyph/cluster changes (desktop only).

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.