Skip to main content

TextRenderer

A class in Root.Township, the global namespace.

Draws 3D text in the world (signs, labels, dock counts) by building a mesh per letter from a TextFont. Client side visuals only: on a headless server setting Text stores the string but builds nothing.

Constructors​

MemberWhat it is
TextRenderer()Unity makes components itself; use AddComponent or spawn a prefab instead of new.

Fields​

43 private and internal fields
MemberWhat it is
private Color activeColorColour applied to letters as they're built; colour tags change it mid-line.
private string actualTextThe text currently built, so a refresh with the same text is skipped.
private TextAlignment alignmentBacking field for Alignment.
private Material androidMaterialMaterial used on Android.
private Color androidTintColorTint used on Android.
private bool bestFitToWidthSingle-line only: scales the text to fit maxWidth, within minScale and maxScale.
private Transform cachedTransformCached transform, used by the distance checker.
private static readonly Dictionary<int, Material> coloredMaterialsShared cache of tinted material copies, keyed by material and colour.
private static readonly Dictionary<int, Mesh> coloredMeshesShared cache of vertex-coloured mesh copies, keyed by mesh and colour.
private Vector2 currentCenterBacking field for CurrentCenter.
private TextFont fontBacking field for Font.
private List<Mesh> generatedMeshes made by this renderer, cleaned on destroy.
private bool hasLineLimitMulti-line only: whether maxLines applies.
private static readonly Regex htmlTagRegexRegex that finds <c:colour> and closing tags in the text.
private static readonly char[] ignoredCharsCharacters that don't log a warning when the font lacks them.
private bool isDelayingInEditorEditor: makes the first refresh call wait, so edits are batched.
private bool isMergingBuilds each line as one merged mesh instead of an object per letter. Always on for baked text.
private bool isMonoTrue while inside a \u0002 monospace section.
private bool isMultiLineWraps the text onto several lines at lineWidth.
private bool isRefreshingInspector button that calls DebugRefresh.
private bool isStaticThe text never moves, so the distance checker caches its position.
private bool isStaticTextBakes the text during prefab bake and deletes the component.
private float lineSpacingVertical gap between lines.
private float lineWidthWrap width for multi-line text, before scale.
private static readonly Logger loggerNLog logger for this class.
private Material materialMaterial used on non-Android platforms.
private int maxLinesMost lines shown when hasLineLimit is on.
private int maxLODLevelHow many LOD levels of staticBatchedLODGroup the baked text joins.
private float maxRenderDistanceSquaredSquared distance from the local player beyond which the text hides; 0 means always shown.
private float maxScaleLargest scale best fit may use.
private float maxWidthWidth best fit scales the text to.
private static readonly List<Color> meshColoringScratch list of vertex colours used by GetMeshForColor.
private float minScaleSmallest scale best fit may use.
private readonly HashSet<Renderer> renderersRenderers created for the current text.
private float scaleBacking field for Scale.
private ShadowCastingMode shadowCastingModeShadow mode for the letter renderers.
private float spacingExtra space added to each character's advance.
private LODGroup staticBatchedLODGroupLOD group the baked text renderers are added to during static batching.
private bool supportsHTMLTagsBacking field for SupportsHtmlTags; enables <c:colour> tags, which need a vertex colour material.
private string textBacking field for Text.
private Color tintColorTint used on non-Android platforms.
private bool useParentLayerPuts the generated objects on this object's layer.
private TextRenderer.TextVerticalAlignment verticalAlignmentMulti-line only: top, centre or bottom alignment of the block.

Properties​

MemberWhat it is
TextAlignment Alignment { get; set; }Horizontal alignment (left, centre, right). Takes effect on the next refresh.
Color Color { get; set; }Tint colour (a separate value on Android). Setting a new colour forces a rebuild.
Vector2 CurrentCenter { get; }Centre of the rendered text in local space, worked out on the last rebuild.
float CurrentHeight { get; private set; }Height of the rendered text after scaling, from the last rebuild.
float CurrentLineWidth { get; private set; }Width of the rendered line before scaling, from the last rebuild.
float CurrentLineWidthScaled { get; }CurrentLineWidth times Scale.
Material EditorMaterial { set; }Write only. Sets both the normal and Android material.
Color EditorTintColor { set; }Write only. Sets both the normal and Android tint colour.
TextFont Font { get; set; }The TextFont used to build letters.
bool IsDuringEditorBake { get; set; }Set while the text is being baked into static meshes at build time. Clearing is skipped during it.
bool IsQueued { get; private set; }Android only: true while the text waits in the shared queue that spreads rebuilds over frames.
bool IsVisible { get; private set; }Whether the text is shown. With a max render distance set, it turns off when the local player is far away.
Material Material { get; }Material for the letters, with a separate one on Android.
int MaxLines { get; set; }Line limit for multi-line text. Unlimited unless the line limit option is on.
float MaxScale { get; set; }Largest scale best fit to width may use.
float MaxWidth { get; set; }Width best fit to width scales the text into.
float MinScale { get; set; }Smallest scale best fit to width may use.
IEnumerable<Renderer> Renderers { get; }The renderers of the generated letters.
float Scale { get; set; }Text scale. Takes effect on the next refresh.
bool SupportsHtmlTags { get; set; }When on, c colour tags in the text are applied. Needs a vertex colour material.
string Text { get; set; }The text to show. Setting it unescapes sequences such as \n and refreshes.
2 private and internal properties
MemberWhat it is
private bool IBakeable.IsBaked { get; set; }Set once the prefab bake has run.
private int IBuildRendererBakeable.SortingOrder { get; }Always 0.

Events​

MemberWhat it is
event Action OnFinishedRenderingAndroid only: raised when a queued rebuild finishes.
event Action OnUpdatedTextRaised after each rebuild of the text mesh.

Methods​

MemberWhat it is
void Clear()Removes the generated letters and empties the text.
void OnValidateSetText(string text)Sets the text without unescaping and refreshes.
void Refresh(bool isForced = false)Rebuilds the letters if the text changed and the text is visible, or always when forced. Skipped on headless servers unless forced.
void SetColor(Color color)Changes the tint and swaps the material on existing letters without rebuilding them.
void SetupTextAndColor(string text, Color color)Sets the tint without a rebuild, then sets Text. If the text is unchanged the new colour does not show until a forced refresh.
void SetVisibility(bool isVisible)Shows or hides the letter renderers, and refreshes when shown.
25 private and internal methods
MemberWhat it is
private void AlignTextLine(float lineWidth, int lineNumber, int lineCount, Transform lineParent)Scales and positions a finished line for the alignment, line number and vertical alignment; with bestFitToWidth it first sets scale to fit maxWidth.
private void AlignTextLine(float lineWidth, int lineNumber, int lineCount, List<Vector3> vertices, int startIndex)Scales and positions a finished line for the alignment, line number and vertical alignment; with bestFitToWidth it first sets scale to fit maxWidth.
private void IBakeable.Bake()Prefab bake: builds the text as merged static meshes, adds them to the static LOD group, then removes this component.
private void IBuildRendererBakeable.Bake(bool isSaving)Prefab bake: builds the text as merged static meshes, adds them to the static LOD group, then removes this component.
private void IBuildRendererBakeable.Clean()Empty build-bake step.
private Vector3 ConvertLinearScale()The line scale to use: uniform, but with z left at 1 on Android.
private float CreateLetterMesh(string text, float currentLineWidth, int i, GameObject letter, Mesh mesh, Material material, Transform letterTransform, float characterWidth)Adds one letter at the current line offset, either as its own renderer object or into the merged vertex lists, and returns the new line width.
private float CreateLetterMesh(string text, float currentLineWidth, int i, LetterMesh letterMesh, List<Vector3> vertices, List<Vector3> normals, List<int> indices, float characterWidth)Adds one letter at the current line offset, either as its own renderer object or into the merged vertex lists, and returns the new line width.
private void CreateMultiline(Material instancedMaterial)Wraps the text into lines no wider than lineWidth (breaking on spaces and new lines), draws up to MaxLines of them and works out height and centre.
private float CreateTextLine(string text, int lineNumber, int lineCount, List<Vector3> vertices, List<Vector3> normals, List<int> indices, List<Color> colors)Adds one line's letters to the merged vertex, normal, index and colour lists, applying colour tags when supportsHTMLTags is on.
private void DebugRefresh()Inspector button: forces a refresh.
private void DrawGizmoLine(float maxWidth)Draws the width guide line for the current alignment.
private float DrawTextLine(string text, int lineNumber, int lineCount, Material material, out float height, out float maxHeight)Builds one line of text under a new Line N child, as one object per letter or one merged mesh, and returns its width.
private int GetColorObjectHash(Object targetObject, Color color)Hash of an object and a colour, used as the key for the coloured material and mesh caches.
private Material GetMaterialForColor(Material material, Color color)Returns a cached copy of the material tinted to the colour, making it on first use.
private Mesh GetMeshForColor(Mesh mesh, Color color)Returns a cached copy of the mesh with all vertex colours set to the colour.
private float GetWidth(char character)Advance width of a character in the font plus spacing. Character \u0002 toggles monospace mode, in which every character takes a space's width.
private void InternalClear()Destroys the generated letter objects and forgets the rendered text.
private void InternalRefresh()Rebuilds the text meshes now, sets width, height and centre, and raises OnUpdatedText (and OnFinishedRendering after an Android queue wait).
private void OnDestroy()Cleans up generated meshes.
private void OnDisable()Clears the text objects and stops distance checks.
private void OnDrawGizmosSelected()Draws the best-fit or multi-line width guide.
private void OnEnable()Registers for distance checks when it has a render distance; otherwise refreshes right away.
private void OnValidate()Keeps maxWidth non-negative and turns off bestFitToWidth when multi-line.
private void Reset()Editor: fills in the default Vinque font and metal material.

Used in​

Members of other types that take, return or hold a TextRenderer:

AchievementBoard.title, AchievementItem.textRenderer, CaveTeleporter.costRenderer, CosmeticRotatingSlot.indexText, MainMenuShopInterface.accountBalanceText, MainMenuShopItem.costText, MainMenuShopItem.itemName, ShopInterface.balanceText, ShopInterface.totalCost, ShopInterfaceItem.costText, ShopInterfaceItem.nameText, CommunalStorage.localAllowance, DockVisual.countLabel3D, PooledDockVisual.countLabel3D, PooledDockVisual.CountLabel3D, InfoBoard.renderer, AssistedSpawnCommandAction.progressText, CustomScroller.textSides, CustomScroller.valueText, EnumMenuSettingBase.valueText, MenuGameSetting<T>.displayNameText, ScrollerEnumMenuSetting.textSides, ScrollerSelector.textSides, ServerCommandAction.buttonText, ServerMultiCommandAction.buttonText, StandardFloatAsEnum.textSides, StandardFloatAsEnum.valueText, UserToken.username, ConfirmPopupPanel.messageText, InputField.textVisuals, ListElementWithButtonAndExtraText.extraText, ListElementWithButtonAndExtraText.ExtraText, OptionsPanel.text, RecentPlayerPanelListElement.thirdLine, CreateServerPanel.canCreateText, FriendsInvitesPanel.emptyListText, FriendsListPanel.emptyListText, FriendsRequestsPanel.emptyListText, GroupInfoTab.infoText, GroupMembersPage.emptyListText, GroupMembersPage.tooManyMembersText, InboxPanel.infoText, IncomingGroupRequestPage.emptyListText, OculusFriendsListPanel.emptyListText, OutgoingGroupInvitesPage.emptyListText, PlayerReportInboxInfoPanel.actionTakenAtText, PlayerReportInboxInfoPanel.actionTakenByText, PlayerReportInboxInfoPanel.actionTakenText, PlayerReportInboxInfoPanel.reasonText, PlayerReportInboxInfoPanel.reportedUserText, PlayerReportInboxInfoPanel.reporterText, PlayerReportInboxInfoPanel.serverText, PlayerReportInboxInfoPanel.timeText, PlayerReportSummaryPanel.actionTakenAtText, PlayerReportSummaryPanel.actionTakenByText, PlayerReportSummaryPanel.actionTakenText, PlayerReportSummaryPanel.reasonText, PlayerReportSummaryPanel.reportedUserText, PlayerReportSummaryPanel.reporterText, PlayerReportSummaryPanel.serverText and 88 more.