因为Unity2019开始,Text中的顶点信息进行了优化,富文本以及一些不可见字符不参与统计。所以我们在使用顶点数据时,也要从文本中过滤掉这些字符,以便和public override void ModifyMesh(VertexHelper vh)
中的顶点数据进行匹配。
这里发现,在不可见字符中,'\r'
字符比较特殊,VertexHelper中会包含该字符的顶点数据。
示例代码:
using System;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
[ExecuteAlways]
[RequireComponent(typeof(Text))]
public class TextVertsChecker : BaseMeshEffect
{
/// <summary>
/// 关联的文本组件
/// </summary>
public Text Text => GetComponent<Text>();
protected override void Awake()
{
base.Awake();
Text.text = "测试\r\n对顶点数据的影响";
}
public override void ModifyMesh(VertexHelper vh)
{
//获取跟顶点数据关联的字符串
var vertStr = GetVertString(Text.cachedTextGenerator, Text.text);
//顶点数据量
var vertCount = Text.cachedTextGenerator.vertexCount >> 2; //vh.currentVertCount >> 2;
//在text没有将文本渲染完全的情况下,顶点数据量是可能大于关联字符数量的
Debug.Log($"顶点数据量: {vertCount} 关联字符数量: {vertStr.Length}");
}
/// <summary>
/// 提取顶点数据关联的字符串
/// </summary>
/// <param name="tg"></param>
/// <param name="input"></param>
/// <returns></returns>
string GetVertString(TextGenerator tg, string input)
{
StringBuilder sb = new StringBuilder();
//针对Text组件范围太小,导致部分字符无法显示的情况进行了优化
var count = Math.Min(tg.characterCount, input.Length);
for (int i = 0; i < count; i++)
{
var info = tg.characters[i];
var c = input[i];
if (info.charWidth > 0 || '\r' == c)
{
sb.Append(c);
}
}
return sb.ToString();
}
}