Version: 2018.2
Ассет текста (Text Asset)
Текстурные компоненты

Шрифт (Font)

Шрифты (Fonts) можно в компонентах GUI Text или Text Mesh. Для этого нужно создать или импортировать файлы шрифтов.

Импортирование файлов шрифтов

Для добавления шрифта в проект, нужно положить файл со шрифтом в папку Assets. Unity автоматически определит и импортирует этот файл. Поддерживаются следующие форматы шрифтов: TrueType Fonts (.ttf) и OpenType Fonts (.otf).

Для изменения размера (Size) и других свойств шрифта, нужно выделить его файл в окне Project View. Откроется список доступных настроек в окне (Import Settings) инспектора (Inspector).

Import Settings for a font
Import Settings for a font
Свойство: Функция:
Font Size Размер шрифта. По аналогии с размерами шрифта в любом текстовом редакторе
Rendering mode Способ рендеринга шрифтов, определяющий, каким образом Unity будет сглаживать символы.
Character Набор символов, которые будут импортированы в текстуру шрифта.
В случае, если выбран вариант Dynamic, Unity будет использовать сам файл шрифта (а не текстуру с символами) для отрисовки символов (подробнее ниже).

Дополнительные настройки импорта для динамических шрифтов (dynamic fonts)

Свойство: Функция:
Include Font Data Свойство определяет, будет ли шрифт упакован при использовании режима Dynamic Font. Если включено, TTF файл со шрифтом будет включен в конечную сборку приложения. Но если предполагается, что этот шрифт уже установлен на устройства конечных пользователей, это свойство можно выключить. Стоит отметить, что на шрифты распространяются законы об авторских правах. По этой причине в сборку можно включать только те шрифты, на которые у вас есть лицензия, или которые вы создали сами.
Font Names Список запасных шрифтов для “отката”, в случае если текущий шрифт не поддерживает определенные символы, или на устройстве пользователя нет требуемого шрифта (подробнее ниже).

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. Adjusting the font size effectively changes how many pixels are used for each glyph in this generated texture. Text Mesh 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)

Если установить свойство Characters в настройках импорта шрифта как Dynamic, Unity не будет генерировать текстуру, включающую все символы шрифта. Вместо этого Unity будет создавать текстуру шрифта “на лету” с помощью движка FreeType. Преимуществом данного подхода является уменьшенный размер конечной сборки приложения и экономия видео памяти. Это особенно заметно при использовании стандартных шрифтов, которые часто уже присутствуют в системе (не требуется включать файл шрифта в сборку), при использовании азиатских языков или при больших размерах шрифта (обычный подход с использованием текстур шрифта приведет к существенному увеличению размеров этих текстур).

Если при отрисовке текста Unity не может найти указанный шрифт (если не было включено свойство Include Font Data и шрифт не установлен на устройстве пользователя), или шрифт не включает в себя требуемые символы (например при попытке отрисовать азиатские иероглифы с помощью латинского шрифта), Unity будет перебирать все шрифты из списка Font Names пока найдет шрифт, в котором присутствует требуемый символ. Если ни один из перечисленных шрифтов не подходит, Unity будет использовать собственный список заранее заданных запасных шрифтов. В нем есть наиболее общие международные шрифты, которые устанавливаются на текущую платформу по умолчанию.

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 256x128, 4 characters across, 2 down (so 64x64), 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 128x128, 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
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 GUIText or Text Mesh, you can enter unicode characters into the Component’s Text 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. 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, a GUIText, 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.

GUIText and Text Mesh

If you are using a GUIText or a Text Mesh, you can change its color by using a custom Material 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.

UnityGUI

If you are using UnityGUI scripting to display your font, you have much more control over the font’s color under different circumstances. To change the font’s color, you create a GUISkin from Assets > Create > GUI Skin, and define the color for the specific control state, e.g. Label > Normal > Text Color. For more details, please read the GUI Skin page.

Советы

  • To display an imported font select the font and choose GameObject > Create Other > 3D Text.
  • You can reduce the generated texture size for fonts by using only lower or upper case characters.
Ассет текста (Text Asset)
Текстурные компоненты
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961