Font assets
To add a font to your project you need to place the font file in your Assets folder. Unity will then automatically import it. Supported Font formats are TrueType Fonts (.ttf files) and OpenType Fonts (.otf files).
To change the Size of the font, highlight it in the Project View and you have a number of options in the Import Settings 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 .
Import Settings for a font
| Property: | Function: |
|---|---|
| Font Size | The size of the font, based on the sizes set in any word processor. |
| Rendering mode | The font rendering mode, which tells Unity how to apply smoothing to the glyphs. |
| Character | The character set of the font to import into the font texture |
| Setting this mode to Dynamic causes Unity to embed the font data itself and render font glyphs at runtime (see below). |
Import Settings specific to dynamic fonts
| Property: | Function: |
|---|---|
| Include Font Data | This setting controls the packaging of the font when used with Dynamic font property. When selected the TTF is included in the output of the build. When not selected it is assumed that the end user will have the font already installed on their machine. Note that fonts are subject to copyright and you should only include fonts that you have licensed or created for yourself. |
| Font Names | A list of fallback fonts to use when fonts or characters are not available (see below). |
After you import the font, you can expand the font in Project View to see that it has auto-generated some assets. Two assets are created during import: “font material” and “font texture”. Unlike many applications you might be familiar with, fonts in Unity are converted into textures, and the glyphs that you display are rendered using textured quads A primitive object that resembles a plane but its edges are only one unit long, it uses only 4 vertices, and the surface is oriented in the XY plane of the local coordinate space. More info
See in Glossary . Adjusting the font size effectively changes how many pixels The smallest unit in a computer image. Pixel size depends on your screen resolution. Pixel lighting is calculated at every screen pixel. More info
See in Glossary are used for each glyph in this generated texture. Text Mesh The main graphics primitive of Unity. Meshes make up a large part of your 3D worlds. Unity supports triangulated or Quadrangulated polygon meshes. Nurbs, Nurms, Subdiv surfaces must be converted to polygons. More info
See in Glossary assets are 3d geometry textured with these auto-generated font textures. You will want to vary the size of the font to make these assets look crisp.
Dynamic fonts
When you set the Characters drop-down in the Import Settings to Dynamic, Unity will not pre-generate a texture with all font characters. Instead, it will use the FreeType font rendering engine to create the texture on the fly. This has the advantage that it can save in download size and texture memory, especially when you are using a font which is commonly included in user systems, so you don’t have to include the font data, or when you need to support asian languages or large font sizes (which would make the font textures very large using normal font textures).
When Unity tries to render text with a dynamic font, but it cannot find the font (because Include Font Data was not selected, and the font is not installed on the user machine), or the font does not include the requested glyph (like when trying to render text in east Asian scripts using a latin font, or when using styled bold/italic text), then it will try each of the fonts listed in the Font Names field, to see if it can find a font matching the font name in the project (with font data included) or installed on the user machine which has the requested glyph. If none of the listed fallback fonts are present and have the requested glyph, Unity will fall back to a hard-coded global list of fallback fonts, which contains various international fonts commonly installed on the current runtime platform.
Note that some target platforms (WebGL, some consoles) do not have OS default fonts Unity can access for rendering text. For those platforms, Include Font Data will be ignored, and font data will always be included. All fonts to be used as fallbacks must be included in the project, so if you need to render international text or bold/italic versions of a font, you need to add a font file which has the required characters to the project, and set up that font in the Font Names list of other fonts which should use it as fallbacks. If the fonts are set up correctly, the fallback fonts will be listed in the Font Importer inspector, as References to other fonts in project.
Default font asset
The default font asset is a dynamic font which is set up to use Arial. If Unity can’t find the Arial font on your computer (for example, if you don’t have it installed), it will fall back to a font bundled with Unity called Liberation Sans.
Liberation Sans looks like Arial, but it does not include bold or italic font styles, and only has a basic Latin character set — so styled text or non-latin characters may fall back to other fonts or fail to render. It does however have a license which allows it to be included in player builds.
Custom fonts
To create a custom font select ‘Create->custom font’ from the project window. This will add a custom font asset to your project library.

The Ascii Start Offset field is a decimal that defines the Ascii index you would like to begin your Character Rects index from. For example, if your Ascii Start Offset is set to 0 then the capital letter A will be at index 65 but if the Ascii Start Offset is set to 65 then the letter A will be at index 0. You can consult the Ascii Table here but you should bear in mind that custom font uses the decimal ascii numbering system.
Tracking can be set to modify how close each character will be to the next character on the same line and Line spacing can be set to define how close each line will be to the next.
To create a font material you will need to import your font as a texture then apply that texture to a material, then drag your font material onto the Default Material section.
The Character Rects section is where each character of your font is defined.

The Size field is for defining how many characters are in your font.
Within each Element there is an index field for the ascii index of the character. This will be an integer that represents the character in this element.
To work out the UV values you need to figure out how your characters are positioned on a scale of 0 to 1. You divide 1 by the number of characters on a dimension. For example if you have a font and the image dimensions on it are 256×128, 4 characters across, 2 down (so 64×64), then UV width will be 0.25 and UV height will be 0.5.
For UV X and Y, it’s just a matter of deciding which character you want and multiplying the width or height value times the column/row of the letter.
Vert size is based on the pixel size of the characters e.g. your characters are each 128×128, putting 128 and –128 into the Vert Width and Height will give properly proportioned letters. Vert Y must be negative.
Advance will be the desired horizontal distance from the origin of this character to the origin of the next character in pixels. It is multiplied by Tracking when calculating the actual distance.
Example of custom font inspector with values
Unicode support
Unity has full unicode support. Unicode text allows you to display German, French, Danish or Japanese characters that are usually not supported in an ASCII character set. You can also enter a lot of different special purpose characters like arrow signs or the option key sign, if your font supports it.
To use unicode characters, choose either Unicode or Dynamic from the Characters drop-down in the Import Settings. You can now display unicode characters with this font. If you are using a Text Mesh A Mesh component that displays a Text string More info
See in Glossary , you can enter unicode characters into the Component’s Text A non-interactive piece of text to the user. This can be used to provide captions or labels for other GUI controls or to display instructions or other text. More info
See in Glossary field in the Inspector.
You can also use unicode characters if you want to set the displayed text from scripting. The C# compiler fully supports Unicode based scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary . You have to save your scripts with UTF–16 encoding. Now you can add unicode characters to a string in your script and they will display as expected in UnityGUI or a Text Mesh.
Note that surrogate pairs are not supported.
Changing Font Color
There are different ways to change the color of your displayed font, depending on how the font is used.
Text Mesh
If you are using a Text Mesh, you can change its color by using a custom Material An asset that defines how a surface should be rendered. More info
See in Glossary for the font. In the Project View, click on Create > Material, and select and set up the newly created Material in the Inspector. Make sure you assign the texture from the font asset to the material. If you use the built-in GUI/Text Shader shader for the font material, you can choose the color in the Text Color property of the material.
Font Assets
TextMesh Pro has its own Font asset format. When you add a font – typically a TTF file – to a Unity project, Unity will import it as a font asset. You then have to use the font asset creator to generate a TextMesh Pro font asset from it. Afterwards, you no longer need the original TTF asset. However, it is a good idea to keep it in your project, in case you need to recreate the font asset.
Font Asset Creator
The TextMesh Pro font creation window can be opened in the editor via Window / TextMeshPro — Font Asset Creator. The window presents you with a few font settings, a generate button, a texture preview, and a button to save your new font asset.
Font asset creator settings.
By default, the window is configured to create a signed distance field (SDF) font asset. The generated textures for these fonts contain contour distance information, which looks like grayscale gradients. When rendered with the right shaders, this will produce high-quality text with support for effects like outlines and drop shadows.
When saving font assets, you have to put them in a specific folder, defined in the settings asset. This will ensure that TextMesh Pro can find them and that they are included in builds.
Font Source
You must select a font from which to generate a Text Mesh Pro font asset. The font source is only needed to generate the font asset. It won’t be included in builds, unless you also use it elsewhere or put it in a Resources folder. The Text Mesh Pro package includes ARIAL, Bangers, and IMPACT as example font sources.
Font Size
You can control the font’s point size that will be used to generate the font’s texture. You can either manually set a custom size or use automatic sizing. Auto Sizing will try to use the largest point size possible while still fitting all characters on the texture. You typically use Auto Sizing for SDF fonts and Custom Size when you want pixel-accurate control over bitmap-only fonts.
Auto vs. custom font size.
Font Padding
Characters in the font texture need some padding between them so they can be rendered separately. This padding is specified in pixels.
Padding also creates room for the SDF gradient. The larger the padding, the smoother the transition, which allows for higher-quality rendering and larger effects, like thick outlines. A padding of 5 is often fine for a 512×512 texture.
Padding 0, 5, and 10 for an SDF font.
Packing Method
Optimum packing will find the largest possible automatic font size that still fits all characters in the texture. Fast packing is a bit faster but might end up using a smaller font size. Typically, you use fast when trying out settings and optimum for the final result.
Atlas Resolution
When using an SFD font, a higher resolution results in finer gradients, which produces higher quality text. For most fonts, a 512×512 texture resolution is fine when including all ASCII characters.
When you need to support thousands of character, you will have to use large textures. But even at maximum resolution, you might not be able to fit everything. In that case, you can split the characters by creating multiple font assets. Put the most often used characters in a main font asset, and the others in a fallback font assets.
Character Set
The characters from a font file aren’t automatically included in the font asset. You have to specify which ones you need. You can select a few predefined character sets, or provide a list of characters yourself.
The presets include the visible characters of the ASCII and Extended ASCII character sets. You can also choose common subsets of ASCII, limited to lowercase, uppercase, and only the numbers and symbols.
The other options give you complete control over which characters to include. You can specify character ranges, using either decimal of hexadecimal numbers. Or you can explicitly list each character.
Custom character sets.
You can also use a text asset, which should contain all the characters that you want included in your font. This allows you to save your character set.
Using a character set file.
Be sure to include the space character, unless you really don’t need it.
Font Style
You can choose between a few different font styles. These settings are for bitmap-only fonts. You can configure the styles of SDF fonts via shaders instead. You can choose between bold, italic, bold plus italic, and outline. You can control the strengh of the boldness and the outline.
Font Render Mode
The distance field modes create SDF textures for use with SDF shaders. The characters are sampled at high resolutions to create good gradients. 16x is the default and adequate for typical use. 32x is slower to generate but can produce better quality for complex or small characters.
The other modes directly render characters to bitmaps for use with bitmap-only fonts. Raster mode doesn’t use anti-aliasing while smooth mode does. Both have a variant mode with hinting, which aligns character pixels with texture pixels for a crisper result.
Get Kerning Pairs?
You can choose to copy the kerning data from the font. This data is used to adjust the spacing between specific character pairs, to produce a more visually pleasing result. Note that many fonts do not have kerning pairs.
Font Asset
TextMesh Pro font assets contain all the information that TextMesh Pro needs to layout and render text.
The default ARIAL SDF font asset.
Face Info
Face info contains information about the font asset. You can see the name of the original font, the point size and padding used to generate the asset, and the size of the atlas texture. These values cannot be edited.
Then there are some metrics that are extracted from the font, which you can adjust to fine-tune the font or to correct weird values. Sometimes fonts are designed with strange metrics which you’ll have to tweak to make it usable.
Line metrics.
The basline is the horizontal line on which characters sit. The ascender describes how far above the baseline characters can extend, which also defines the top of a line. The descender does the same, but below the baseline. The line height defines the distance between the tops of consecutive lines. If it is larger than the size of the ascender and descender combined, there will be a gap between lines. If it is smaller, then characters from different lines could overlap.
Underline dictates where underlines will be placed, relative to the baseline.
The superscript and subscript offsets are used to adjust the baseline for superscript and subscript text. Their size is a factor that is used to scale such text, relative to the normal font size.
Font Sub-Assets
Each font asset also contains two sub-assets. These are its texture atlas and its default material. You should not edit these directly.
Font Weights
You can control how bold and italic changes the appearance of the font. It is possible to select different font assets to be used for bold, italic, and bold with italic font variants. If you do not specify font variants, fake bold and italics will be used instead.
Font weight settings.
You can also adjust the weight and spacing of the text. The weight is added to the dilation used by the SDF shaders. The spacing is added to the space between characters. You can define these values for both the normal and fake bold style.
The Italic Style is used to create a fake italic font variant by slanting the character sprites. You can control the strength of this effect.
Tab Multiple controls the tab size. It is defined as a multiple of the width of the font’s space character.
Fallback Font Assets
Each font asset contains a limited amount of characters. Sometimes, a font that you’re using lacks a character that you need. When that happens, the fallback font list will be searched until a font is founds that does include the missing character. The text object will then use that font to render it.
Fallback font list.
You can also use this feature to distribute fonts over multiple textures. Or to automatically use different fonts for certain characters. However, keep in mind that searching the list for missing characters requires extra work. Also, additional fonts require additional draw calls.
Glyph Info
Here you can inspect the data of each character in the font, and tweak it if necessary. The character list is split into pages, which you can navigate through via the buttons at the top and bottom. You can also filter the list, based on character codes. Click on an entry to make it active. This allows you to edit, copy, and remove it.
Glyph info.
The X, Y, W, and H values define character’s rectangular area in the font atlas. The OX and OY offsets control the placement of the character’s sprite, defined at its top-left corner relative to its origin on the baseline. The ADV value controls how far to advance along the baseline before placing the next character. Finally, SF is a scale factor which you can use to ajust the size of the character.
Kerning Table Info
The kerning table is either imported from a font or made manually. The table is split into pages, which you can navigate through via the buttons at the bottom. Each entry is a kerning pair with a left and a right character. The offset is relative to where the right character would normally start. A positive value pushes the characters further apart, while a negative value pulls them together.
Part of a kerning table.
There are many fonts that do not include kerning pairs. You can add them manually, by specifying either the characters or their decimal character codes, plus their offset adjustment.
Как добавить шрифт в TextMeshPro в Unity?
Перетаскиваете ваш шрифт в Unity. Затем Window — Text Mesh Pro — Font Asset Creator. В верхнем поле выбираете шрифт и жмёте Generate Font Atlas и выбираете папку куда сохранить ассет. Если нужно с кириллицей, то в поле Character Set выбираем Unicode Range (Hex) и в поле ниже прописываем 0400-04ff, если нужно ещё с английскими буквами, символами и цифрами, то 0000-04ff
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.3.11.43300
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Четыре способа работы с текстом 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. Можете использовать его в качестве примера. Если вы сможете написать конвертер, который будет достаточно хорош для ваших целей, то он позволит перенести задачу создания спрайтового шрифта в более эффективный инструмент, что сэкономит время.