Get started with text
UI Toolkit uses TextCore to render text, a technology based on TextMesh Pro. TextCore allows advanced styling capabilities and can render text clearly at various point sizes and resolutions. It takes advantage of Signed Distance Field (SDF) font rendering, which can generate font assets that look crisp even when transformed and magnified.
This example demonstrates how to style text in UI (User Interface) Allows a user to interact with your application. Unity currently supports three UI systems. More info
See in Glossary Builder, create and apply static and dynamic font assets, use rich text tags and custom style sheets to style text, and create a Panel Text Settings asset to manage the text settings for a panel.
Note: For demonstration purposes, this guide uses a runtime UI. The instructions to create font assets and a style sheet also apply to Editor UI. However, you can’t change the default Panel Text Settings for Editor UI in the current release.
Prerequisites
This guide is for developers familiar with the Unity Editor, UI Toolkit, and C# scripting. You are recommended to have a basic understanding of the following:
Create a Panel Text Settings asset
Start with a runtime UI and create a Panel Text Settings asset that manages text settings for the panel. You also create a Resources folder and sub-folders to store font assets and custom style sheets.
- Follow the steps in Get started with Runtime UI to create a simple runtime UI.
- In the Assets folder, create a Resources folder.
- Right-click in the Assets\UI Toolkit folder, and select Create > UI Toolkit > Text Settings to create a UITK Text Settings.asset . The Inspector window for UITK Text Settings.asset shows the default path names for the font asset, Text Style Sheets asset, Sprite asset, and Color Gradient presets.
- In the Resources folder, create two folders named Fonts & Materials and Text Style Sheets .
Style text with UI Builder
Use UI Builder to style the Toggle text to be bold and italic, and have a font size of 12px . For more information, see Style text with USS.
- Double-click SimpleRuntimeUi.uxml to open it in UI Builder.
- In the Inspector A Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary window for the Toggle control, select Text. - In the Font Style field, select B and I.
- In the Size field, enter 12.
Create a static font asset
Create a static font asset and apply it to the Button control. For a static font asset, you don’t need to include the source font file in the build. However, you must generate atlas for all the characters in the Button’s display text. The display text is This is a Button and you will add a * in the text, so you generate atlas for TBhinostua* .
Download the Lato font package from Google Fonts.
Unzip the font package file and place Lato-Regula.ttf in your project’s Assets folder.
In the Inspector window for the font file, confirm the following:
- Include Font Data is enabled.
- Character is set to Dynamic.
In the Project window, right-click Lato-Regula.ttf and select Create > Text > Font Asset. This creates a dynamic font asset called Lato-Regula SDF.asset .
In the Inspector window for Lato-Regula SDF.asset , set the Atlas Population Mode to Static.
Click Update Atlas Texture.
In the Font Asset Creator window, from the Character Set list, choose Custom Characters.
In the Custom Characters List box, enter TBhinostua* .
Click Generate Font Atlas.
Save your changes.
Place Lato-Regula SDF.asset in the Assets\Resources\Fonts & Materials folder.
Double-click SimpleRuntimeUi.uxml to open it in UI Builder.
In the Inspector window for the Button control, select Text > Font Asset > Lato-Regula SDF.
Create a dynamic font asset
Create a dynamic font asset and apply it to the TextField control A TextField control displays a non-interactive piece of text to the user, such as a caption, label for other GUI controls, or instruction. More info
See in Glossary . For a dynamic font asset, you must include the source font file in the build. Import the source font file directly to the path set for font.
Download the Roboto font package from Google Fonts.
Unzip the font package file and place Roboto-Regular.ttf in your project’s Assets\Resources\Fonts & Materials folder.
In the Inspector window for the font file, confirm the following:
- Include Font Data is enabled
- Character is set to Dynamic
Right-click Roboto-Regular.ttf and select Create > Text > Font Asset. This creates a dynamic font asset called Roboto-Regular SDF.asset .
Double-click SimpleRuntimeUi.uxml to open it in UI Builder.
In the TextField control’s Inspector window, select Text > Font Asset > Roboto-Regular SDF.
Style with rich text tags
Use rich text tags to style text in the Label control.
Note: In the current release, rich text tags aren’t supported for TextField.
- Double-click SimpleRuntimeUi.uxml to open it in UI Builder.
- In the Inspector window for the Label control , change Text to This is a <font-weight=700><size=2em><color=#FF0000>*Label*</color></size></font-weight> . This makes the word Label big, red, bold, and with an asterisk on either side of it.
- Make sure Enable Rich Text is selected.
The label text looks like the following in the Viewport The user’s visible area of an app on their screen.
See in Glossary window:
Label text preview shows the word “Label” as big, red, and with an asterisk to either side.
Style with style sheets
To apply the same style for Label to Button , create a custom style sheet, and apply the style to both words.
Right-click in the Assets\Resources\Text Style Sheets folder and select Create > Text > Text StyleSheet. This creates a Text StyleSheet.asset in the path you set in the Panel Text Settings asset.
In the Inspector window for Text StyleSheet.asset , do the following:
- In Name, enter ExampleStyle .
- In Opening Tags, enter <font-weight=700><size=2em><color=#FF0000>* .
- In Closing Tags, enter *</color></size></font-weight> .
In the Inspector window for UITK Text Settings.asset , from the Default Style Sheet list, select Text StyleSheet.
Double-click SimpleRuntimeUi.uxml to open it in UI Builder.
In the Label control’s Inspector window, change Text to <s>This is a <style="ExampleStyle">Label</style> .
Make sure Enable Rich Text is selected.
In the Button control’s Inspector window, change Text to <s>This is a <style="ExampleStyle">Button</style> .
Make sure Enable Rich Text is selected.
Enter Play mode and check the text in the runtime UI.
In the text field, enter some random characters. For a dynamic font asset, the font atlas are dynamically generated as you enter text in the text field.
Get started with text
UI Toolkit uses TextCore to render text, a technology based on TextMesh Pro. TextCore allows advanced styling capabilities and can render text clearly at various point sizes and resolutions. It takes advantage of Signed Distance Field (SDF) font rendering, which can generate font assets that look crisp even when transformed and magnified.
This example demonstrates how to style text in UI (User Interface) Allows a user to interact with your application. Unity currently supports three UI systems. More info
See in Glossary Builder, create and apply static and dynamic font assets, use rich text tags and custom style sheets to style text, and create a Panel Text Settings asset to manage the text settings for a panel.
Note: For demonstration purposes, this guide uses a runtime UI. The instructions to create font assets and a style sheet also apply to Editor UI. However, you can’t change the default Panel Text Settings for Editor UI in the current release.
Prerequisites
This guide is for developers familiar with the Unity Editor, UI Toolkit, and C# scripting. Before you start, get familiar with the following:
Create a Panel Text Settings asset
Start with a runtime UI and create a Panel Text Settings asset that manages text settings for the panel. You also create a Resources folder and sub-folders to store font assets and custom style sheets.
- Follow the steps in Get started with Runtime UI to create a simple runtime UI.
- In the Assets folder, create a Resources folder.
- Right-click in the Assets\UI Toolkit folder, and select Create > UI Toolkit > Text Settings to create a UITK Text Settings.asset . The Inspector window for UITK Text Settings.asset shows the default path names for the font asset, Text Style Sheets asset, Sprite asset, and Color Gradient presets.
- In the Resources folder, create two folders named Fonts & Materials and Text Style Sheets .
Style text with UI Builder
Use UI Builder to style the Toggle text to be bold and italic, and have a font size of 12px . For more information, see Style text with USS.
- Double-click SimpleRuntimeUi.uxml to open it in UI Builder.
- In the Inspector A Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary window for the Toggle control, select Text. - In the Font Style field, select B and I.
- In the Size field, enter 12.
Create a static font asset
Create a static font asset and apply it to the Button control. For a static font asset, you don’t need to include the source font file in the build. However, you must generate atlas for all the characters in the Button’s display text. The display text is This is a Button and you will add a * in the text, so you generate atlas for TBhinostua* .
Download the Lato font package from Google Fonts.
Unzip the font package file and place Lato-Regula.ttf in your project’s Assets folder.
In the Inspector window for the font file, confirm the following:
- Include Font Data is enabled.
- Character is set to Dynamic.
In the Project window, right-click Lato-Regula.ttf and select Create > Text > Font Asset. This creates a dynamic font asset called Lato-Regula SDF.asset .
In the Inspector window for Lato-Regula SDF.asset , set the Atlas Population Mode to Static.
Click Update Atlas Texture.
In the Font Asset Creator window, from the Character Set list, choose Custom Characters.
In the Custom Characters List box, enter TBhinostua* .
Click Generate Font Atlas.
Save your changes.
Place Lato-Regula SDF.asset in the Assets\Resources\Fonts & Materials folder.
Double-click SimpleRuntimeUi.uxml to open it in UI Builder.
In the Inspector window for the Button control, select Text > Font Asset > Lato-Regula SDF.
Create a dynamic font asset
Create a dynamic font asset and apply it to the TextField control A TextField control displays a non-interactive piece of text to the user, such as a caption, label for other GUI controls, or instruction. More info
See in Glossary . For a dynamic font asset, you must include the source font file in the build. Import the source font file directly to the path set for font.
Download the Roboto font package from Google Fonts.
Unzip the font package file and place Roboto-Regular.ttf in your project’s Assets\Resources\Fonts & Materials folder.
In the Inspector window for the font file, confirm the following:
- Include Font Data is enabled
- Character is set to Dynamic
Right-click Roboto-Regular.ttf and select Create > Text > Font Asset. This creates a dynamic font asset called Roboto-Regular SDF.asset .
Double-click SimpleRuntimeUi.uxml to open it in UI Builder.
In the TextField control’s Inspector window, select Text > Font Asset > Roboto-Regular SDF.
Style with rich text tags
Use rich text tags to style text in the Label control.
Note: In the current release, rich text tags aren’t supported for TextField.
- Double-click SimpleRuntimeUi.uxml to open it in UI Builder.
- In the Inspector window for the Label control , change Text to This is a <font-weight=700><size=2em><color=#FF0000>*Label*</color></size></font-weight> . This makes the word Label big, red, bold, and with an asterisk on either side of it.
- Make sure Enable Rich Text is selected.
The label text looks like the following in the Viewport The user’s visible area of an app on their screen.
See in Glossary window:
Label text preview shows the word “Label” as big, red, and with an asterisk to either side.
Style with style sheets
To apply the same style for Label to Button , create a custom style sheet, and apply the style to both words.
Right-click in the Assets\Resources\Text Style Sheets folder and select Create > Text > Text StyleSheet. This creates a Text StyleSheet.asset in the path you set in the Panel Text Settings asset.
In the Inspector window for Text StyleSheet.asset , do the following:
- In Name, enter ExampleStyle .
- In Opening Tags, enter <font-weight=700><size=2em><color=#FF0000>* .
- In Closing Tags, enter *</color></size></font-weight> .
In the Inspector window for UITK Text Settings.asset , from the Default Style Sheet list, select Text StyleSheet.
Double-click SimpleRuntimeUi.uxml to open it in UI Builder.
In the Label control’s Inspector window, change Text to <s>This is a <style="ExampleStyle">Label</style> .
Make sure Enable Rich Text is selected.
In the Button control’s Inspector window, change Text to <s>This is a <style="ExampleStyle">Button</style> .
Make sure Enable Rich Text is selected.
Enter Play mode and check the text in the runtime UI.
In the text field, enter some random characters. For a dynamic font asset, the font atlas are dynamically generated as you enter text in the text field.
Unity UI. Text
Так как во вступлении мы уже упомянули Canvas, то сейчас предлагаю сразу перейти к Unity. Сегодня мы уделим внимание базовому элементу любого интерфейса — Text. Именно этот элемент будет в будущем в кнопках, с его помощью мы будем выводить на экран различные данные, надписи, метрики и т.д. Он прост, но без него никак. Если брать мой опыт в Android, то там кнопка Button наследует TextView, т.е. всё тот же текст.
Добавляет Text
Открываем проект. ПКМ в окошке иерархии и добавляем Text.

Кроме Canvas появился ещё и элемент EventSystem. Как и понятно из названия, он будет отвечать за обработку взаимодействия с интерактивными элементами UI. Но об этом позже.
Теперь в камере вы можете увидеть текст:

В самом же редакторе можно увидеть как рамки Canvas, так и, опять же, Text:


В инспекторе у Text видим несколько компонентов. Самые важные сейчас: Rect Transform отвечает за положение и размеры элемента и Text, где мы можем изменить его содержимое, цвет, шрифт, размер, выравнивание настроить и т.д.
Для начала отдадим дань классике и выведем Hello World!
Сразу видим изменения:

Больше кастомизации для Text!
Теперь давайте изменим цвет, так как его плохо видно. Добавим какой-то свой шрифт. Также изменим выравнивание и размер.
Прежде всего я скачал первый попавшийся на глаза читаемый шрифт и закинул его в новую папку Fonts в Assets: Josefin Sans и поставил флаг в чекбокс Best Fit. Этот параметр регулирует размер текста чтобы он соответствовал размеру элемента.
Меняю цвет, ровняю по центру…


Уже намного лучше.
Но куда интереснее параметр Rich Text. Он позволяет использовать в тексте теги форматирования. Например, можно вывести слова разными цветами. Для этого в поле текста пишем такую конструкцию:
Четыре способа работы с текстом UI в Unity
В процессе преобразования старого кода Unity на основе 2D Toolkit в чистый код Unity я столкнулся с проблемой: в Unity есть замечательная поддержка стандартных форматов шрифтов, но этого всё равно недостаточно, чтобы сравниться поддержкой создания шрифтов из листов спрайтов в tk2d.

Пример спрайтового шрифта
На самом деле, это не очень серьёзная проблема — в конце концов, проще и логичнее вставить готовый шрифт, но я хотел сохранить стиль, похожий на рукописные надписи.
Поэтому я приступил к каталогизации различных опций, которые предоставляет Unity при работе с текстом UI (в том числе недавно приобретённого Unity и встроенного в версию 2018.1 TextMesh Pro). Хотя мои знания типографики довольно узки (а тема эта, похоже, очень сложна), статья позволит вам понять, какие возможности существуют и как их можно использовать.
Стандартный Unity Font Asset

Стандартная поддержка Unity файлов шрифтов .ttf и .otf — простейший и самый популярный способ реализации текста в игре.
Похоже, что внутри он является динамически создаваемым спрайтовым шрифтом. Unity создаёт из шрифта текстуру с заданным размером шрифта.
Источник: шрифты автоматически создаются из файлов .ttf или .otf.
Применение: только для компонентов UI Text
Возможности масштабирования: текст можно свободно масштабировать в компоненте UI Text. Масштабирование самого шрифта увеличивает размер генерируемой из шрифта текстуры, что делает результат более чётким.
Плюсы/минусы: Прост в использовании, но поддерживаются только импортируемые шрифты.
Unity Custom Font

Unity имеет возможность создания произвольных спрайтовых шрифтов, но возможность их масштабирования ограничена.
Источник: Custom Fonts создаются из материала (Material) (который ссылается на Texture) и таблиц символов.
Таблицы символов кажутся мне немного сложными (но думаю, что это проще, чем разбираться с UV-координатами). Кроме того, похоже. не существует GUI-инструмента для их генерации из самого листа спрайтов. У каждого символа есть следующие свойства:
- Index: индекс символа ASCII
- UV texture coordinates: находится в интервале от 0 до 1, обозначает процент ширины и высоты текстуры
- Vert: пиксельные координаты
- Advance: шаг в пикселях перед отрисовкой следующего символа, чем больше значения, тем больше пробелы между символами.
Можно задать масштаб game object, содержащего компонент Text. Однако при этом изменяются границы элемента, поэтому это довольно неудобно, если вы хотите выровнять разные элементы.
Применение: только для компонентов UI Text
Плюсы/минусы: является нативной поддержкой спрайтовых шрифтов в Unity, но размер можно менять только с помощью масштабирования. Нет инструмента для генерации таблиц символов; их необходимо заполнять вручную.
TextMesh Pro Font Asset

В отличие от Unity, в TextMesh Pro есть единый формат для текстовых файлов и спрайтовых шрифтов, и его поведение для обоих типов шрифтов примерно одинаково.
Недостаток шрифтов TextMesh Pro заключается в том, что их можно использовать только с компонентами TextMesh Pro UI. Если вы считаете, что есть причина для использования TextMesh Pro, то лучше принять это решение на ранних этапах проекта и постоянно придерживаться его на протяжении всего проекта. Переделка готового проекта, написанного со стандартными компонентами UI Text, окажется мучительной задачей.
Источник: шрифтовые ресурсы TextMesh Pro создаются из материала (Material) и таблиц символов, почти как Custom Fonts Unity.
Таблицы символов указываются только в пиксельных координатах, а не в UV, поэтому они проще и точнее, чем произвольные шрифты Unity. Кроме того, существует инструмент Font Asset Creator, создающий шрифтовой ресурс TextMesh Pro из файла шрифта. Однако для спрайтовых шрифтов процесс всё равно довольно медленный.

Опции масштабирования: масштабировать шрифт TextMesh Pro можно в компоненте TextMesh Pro UI, меняя размер шрифта и без необходимости изменения масштаба game object. По этой причине, если мне нужно использовать спрайтовый шрифт, то я предпочитаю TextMesh Pro нативному Unity Text.
Применение: TextMesh Pro — только компоненты Text UI
Плюсы/минусы: более гибкий, чем шрифтовые ресурсы или спрайтовые шрифты Unity, но требует собственного компонента TextMesh Pro UI Text. Отсутствует инструмент для создания таблиц символов из листов спрайтов, их приходится делать вручную.
TextMesh Pro Sprite Asset
Спрайтовые ресурсы TextMesh Pro немного не к месту в этом списке — на самом деле они не являются шрифтовыми ресурсами в том же смысле, что и остальные три типа. Скорее это дополнительная функция, предоставляемая пользователю компонентами TextMesh Pro – Text.
Спрайтовые ресурсы решают проблему смешения стандартного текста с внутриигровыми символами или значками (в качестве примера можно привести символы предметов, используемые внутри инвентаря Final Fantasy).

Применение: компоненты TextMesh Pro – Text UI. Для каждого компонента можно назначить один шрифтовой ресурс TMP и один спрайтовый ресурс TMP.
Для ссылки на значок спрайта в тексте используется тэг <sprite index=#> (где # — индекс спрайта начиная с 0).
Источник: TextMesh Pro Sprite Assets создаются из материала (Material) и таблиц символов. Концептуально они близки к шрифтовым ресурсам TextMesh Pro. Инструмент Sprite Importer немного лучше, чем Font Asset Creator, потому что он может использовать файлы FNT для генерации таблиц символов листов спрайтов. (См. примечания о файлах FNT в следующем разделе.)
Плюсы/минусы: отсутствуют, потому что этот способ на самом деле является побочным преимуществом использования TextMesh Pro. Если вы по какой-то причине хотите использовать этот функционал в проекте. то лучше всего как можно раньше начать применение TextMesh Pro.
Генерация произвольных шрифтов и шрифтовых ресурсов TextMesh Pro из файлов FNT
Это может само по себе стать темой для отдельного поста, об этом точно стоит сказать, потому что благодаря этому создание произвольных шрифтов и шрифтовых ресурсов TextMesh Pro становится гораздо менее монотонным делом.
Основным недостатком создания спрайтовых шрифтов (с помощью средств Unity или шрифтовых ресурсов TextMesh Pro) является то, что отсутствует GUI-инструмент для определения символов из листа спрайтов. По сути, вам приходится вбивать вручную кучу цифр, тестировать шрифт, потом снова повторять, а это очень монотонный процесс.
Но есть и хорошие новости — существует более-менее стандартный текстовый формат для такой информации, который используется во многих GUI-инструментах для создания спрайтовых шрифтов. (Даже я сам написал упрощённую утилиту с частичной поддержкой спецификации FNT.)
Плохая новость заключается в том, что Custom Fonts Unity и шрифтовые ресурсы TextMesh Pro по умолчанию не поддерживают его.
Однако Unity поддерживает концепцию постпроцессоров ресурсов, которые могут считывать «сырые» файлы в проекте и преобразовывать их в ресурсы, используемые в коде. Постпроцессоры ресурсов выполняются при импорте и повторном импорте ресурсов.
Я написал очень простой конвертер FNT-to-TextMesh Pro Font Asset. Можете использовать его в качестве примера. Если вы сможете написать конвертер, который будет достаточно хорош для ваших целей, то он позволит перенести задачу создания спрайтового шрифта в более эффективный инструмент, что сэкономит время.