Version: 2017.4
Auto Layout
Справка по пользовательским интерфейсам

«Обогащенный» текст (Rich Text)

The text for UI elements and text meshes can incorporate multiple font styles and sizes. Rich text is supported both for the UI System and the legacy GUI system. The Text, GUIStyle, GUIText and TextMesh classes have a Rich Text setting which instructs Unity to look for markup tags within the text. The Debug.Log function can also use these markup tags to enhance error reports from code. The tags are not displayed but indicate style changes to be applied to the text.

Формат разметки

Система разметки текста в Unity была создана на основе HTML, однако при этом строгая совместимость со стандартным HTML не подразумевается. Основная идея заключается в том, что фрагменты текста можно заключать в пару согласующихся друг с другом тегов:-

   We are <b>not</b> amused

Как показано на примере выше, тегами называются фрагменты текста, заключенные в угловые скобки: < и >. Текст внутри скобок определяет имя тега (в данном случае это b). Обратите внимание, что тег в конце фрагмента (закрывающий) обладает тем же именем, что и тег в начале (открывающий), однако в нем также содержится символ косой черты /. Теги не видны непосредственно пользователю, однако используются в качестве инструкций по форматированию текста, который они оборачивают. Тег b в примере выше используется, чтобы придать слову «not» жирный стиль шрифта и отобразить текст на экране следующим образом:-

   We are not amused

Размеченный фрагмент текста (включая оборачивающие его теги) также называется элементом.

Вложенные элементы

Существует возможность применять более одного стиля к фрагменту текста при помощи «вложения» одних элементов в другие.

   We are <b><i>definitely not</i></b> amused

Тег i задает фрагменту курсивный стиль шрифта, отображающийся на экране следующим образом:

   We are definitely not amused

Обратите внимание, что порядок закрывающих тегов противоположен порядку открывающих. Причину этого проще понять, если вы примете во внимание тот факт, что внутренние теги не обязательно должны распространяться на весь текст вплоть до последнего элемента

   We are <b>absolutely <i>definitely</i> not</b> amused

дает следующий результат:

   We are absolutely definitely not amused

Параметры тегов

Some tags have a simple all-or-nothing effect on the text but others might allow for variations. For example, the color tag needs to know which color to apply. Information like this is added to tags by the use of parameters:-

   We are <color=green>green</color> with envy

Note that the ending tag doesn’t include the parameter value. Optionally, the value can be surrounded by quotation marks but this isn’t required.

Поддерживаемые теги

The following list describes all the styling tags supported by Unity.

Tag Описание Шестнадцатиричный код Notes
b Renders the text in boldface.    We are <b>not</b> amused.
i Renders the text in italics.    We are <i>usually</i> not amused.
size Sets the size of the text according to the parameter value, given in pixels.    We are <size=50>largely</size> unaffected. Although this tag is available for Debug.Log, you will find that the line spacing in the window bar and Console looks strange if the size is set too large.
Название цвета Sets the color of the text according to the parameter value. The color can be specified in the traditional HTML format.    #rrggbbaa …where the letters correspond to pairs of hexadecimal digits denoting the red, green, blue and alpha (transparency) values for the color. For example, cyan at full opacity would be specified by    <color=#00ffffff>… Another option is to use the name of the color. This is easier to understand but naturally, the range of colors is limited and full opacity is always assumed.    <color=cyan>… The available color names are given in the table below.
Название цвета Шестнадцатиричный код Пример
aqua (same as cyan) #00ffffff
black #000000ff
blue #0000ffff
brown #a52a2aff
cyan (same as aqua) #00ffffff
darkblue #0000a0ff
fuchsia (same as magenta) #ff00ffff
green #008000ff
grey #808080ff
lightblue #add8e6ff
lime #00ff00ff
magenta (same as fuchsia) #ff00ffff
maroon #800000ff
navy #000080ff
olive #808000ff
orange #ffa500ff
purple #800080ff
red #ff0000ff
silver #c0c0c0ff
teal #008080ff
white #ffffffff
yellow #ffff00ff

material

This is only useful for text meshes and renders a section of text with a material specified by the parameter. The value is an index into the text mesh’s array of materials as shown by the inspector.

   We are <material=2>texturally</material> amused

quad

This is only useful for text meshes and renders an image inline with the text. It takes parameters that specify the material to use for the image, the image height in pixels, and a further four that denote a rectangular area of the image to display. Unlike the other tags, quad does not surround a piece of text and so there is no ending tag - the slash character is placed at the end of the initial tag to indicate that it is “self-closing”.

   <quad material=1 size=20 x=0.1 y=0.1 width=0.5 height=0.5 />

This selects the material at position in the renderer’s material array and sets the height of the image to 20 pixels. The rectangular area of image starts at given by the x, y, width and height values, which are all given as a fraction of the unscaled width and height of the texture.

Editor GUI

Rich text is disabled by default in the editor GUI system but it can be enabled explicitly using a custom GUIStyle. The richText property should be set to true and the style passed to the GUI function in question:-

GUIStyle style = new GUIStyle ();
style.richText = true;
GUILayout.Label("<size=30>Some <color=yellow>RICH</color> text</size>",style);
Auto Layout
Справка по пользовательским интерфейсам
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961