Объявление
public void RequestCharactersInTexture(string characters, int size = 0, FontStyle style = FontStyle.Normal);Параметры
characters | Символы, которые должны быть в текстуре шрифта. |
size | Размер запрошенных символов (значение по умолчанию, равное нулю, будет использовать размер шрифта по умолчанию). |
style | Стиль запрошенных символов. |
Описание
Запросить добавление символов в текстуру шрифта (только для динамических шрифтов).
Примечание: вам следует использовать это только тогда, когда вы хотите реализовать собственный рендеринг текста.
Вызовите эту функцию, чтобы запросить Unity, чтобы убедиться, что все символы в строке characters
доступны в текстуре шрифта (и это characterInfo
собственность). Это полезно, когда вы хотите реализовать свой собственный код для отображения динамических шрифтов. Вы можете указать собственный размер и стиль шрифта для символов. Если size
равен нулю (по умолчанию), для этого шрифта будет использоваться размер по умолчанию.
RequestCharactersInTexture может привести к повторной генерации текстуры шрифта, если в ней недостаточно места для добавления всех запрошенных символов. Если текстура шрифта регенерируется, она будет содержать только символы, которые использовались с помощью Font.RequestCharactersInTexture или с использованием функций рендеринга текста Unity во время последнего кадра. Поэтому рекомендуется всегда вызывать RequestCharactersInTexture для любого текста на экране, который вы хотите отобразить с помощью функций рендеринга пользовательских шрифтов, даже если символы в настоящее время присутствуют в текстуре, чтобы убедиться, что они не удаляются во время перестроения текстуры.
Смотрите так же: textureRebuilt, GetCharacterInfo.
using UnityEngine;
using System.Collections;
public class CustomFontMeshGenerator : MonoBehaviour
{
Font font;
string str = "Hello World";
Mesh mesh;
void OnFontTextureRebuilt(Font changedFont)
{
if (changedFont != font)
return;
RebuildMesh();
}
void RebuildMesh()
{
// Generate a mesh for the characters we want to print.
var vertices = new Vector3[str.Length * 4];
var triangles = new int[str.Length * 6];
var uv = new Vector2[str.Length * 4];
Vector3 pos = Vector3.zero;
for (int i = 0; i < str.Length; i++)
{
// Get character rendering information from the font
CharacterInfo ch;
font.GetCharacterInfo(str[i], out ch);
vertices[4 * i + 0] = pos + new Vector3(ch.minX, ch.maxY, 0);
vertices[4 * i + 1] = pos + new Vector3(ch.maxX, ch.maxY, 0);
vertices[4 * i + 2] = pos + new Vector3(ch.maxX, ch.minY, 0);
vertices[4 * i + 3] = pos + new Vector3(ch.minX, ch.minY, 0);
uv[4 * i + 0] = ch.uvTopLeft;
uv[4 * i + 1] = ch.uvTopRight;
uv[4 * i + 2] = ch.uvBottomRight;
uv[4 * i + 3] = ch.uvBottomLeft;
triangles[6 * i + 0] = 4 * i + 0;
triangles[6 * i + 1] = 4 * i + 1;
triangles[6 * i + 2] = 4 * i + 2;
triangles[6 * i + 3] = 4 * i + 0;
triangles[6 * i + 4] = 4 * i + 2;
triangles[6 * i + 5] = 4 * i + 3;
// Advance character position
pos += new Vector3(ch.advance, 0, 0);
}
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uv;
}
void Start()
{
font = Font.CreateDynamicFontFromOSFont("Helvetica", 16);
// Set the rebuild callback so that the mesh is regenerated on font changes.
Font.textureRebuilt += OnFontTextureRebuilt;
// Request characters.
font.RequestCharactersInTexture(str);
// Set up mesh.
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshRenderer>().material = font.material;
// Generate font mesh.
RebuildMesh();
}
void Update()
{
// Keep requesting our characters each frame, so Unity will make sure that they stay in the font when regenerating the font texture.
font.RequestCharactersInTexture(str);
}
void OnDestroy()
{
Font.textureRebuilt -= OnFontTextureRebuilt;
}
}