因?yàn)閁nity2019開始,Text中的頂點(diǎn)信息進(jìn)行了優(yōu)化,富文本以及一些不可見字符不參與統(tǒng)計(jì)。所以我們?cè)谑褂庙旤c(diǎn)數(shù)據(jù)時(shí),也要從文本中過濾掉這些字符,以便和public override void ModifyMesh(VertexHelper vh)中的頂點(diǎn)數(shù)據(jù)進(jìn)行匹配。
這里發(fā)現(xiàn),在不可見字符中,'\r'字符比較特殊,VertexHelper中會(huì)包含該字符的頂點(diǎn)數(shù)據(jù)。
示例代碼:
using System;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
[ExecuteAlways]
[RequireComponent(typeof(Text))]
public class TextVertsChecker : BaseMeshEffect
{
/// <summary>
/// 關(guān)聯(lián)的文本組件
/// </summary>
public Text Text => GetComponent<Text>();
protected override void Awake()
{
base.Awake();
Text.text = "測試\r\n對(duì)頂點(diǎn)數(shù)據(jù)的影響";
}
public override void ModifyMesh(VertexHelper vh)
{
//獲取跟頂點(diǎn)數(shù)據(jù)關(guān)聯(lián)的字符串
var vertStr = GetVertString(Text.cachedTextGenerator, Text.text);
//頂點(diǎn)數(shù)據(jù)量
var vertCount = Text.cachedTextGenerator.vertexCount >> 2; //vh.currentVertCount >> 2;
//在text沒有將文本渲染完全的情況下,頂點(diǎn)數(shù)據(jù)量是可能大于關(guān)聯(lián)字符數(shù)量的
Debug.Log($"頂點(diǎn)數(shù)據(jù)量: {vertCount} 關(guān)聯(lián)字符數(shù)量: {vertStr.Length}");
}
/// <summary>
/// 提取頂點(diǎn)數(shù)據(jù)關(guān)聯(lián)的字符串
/// </summary>
/// <param name="tg"></param>
/// <param name="input"></param>
/// <returns></returns>
string GetVertString(TextGenerator tg, string input)
{
StringBuilder sb = new StringBuilder();
//針對(duì)Text組件范圍太小,導(dǎo)致部分字符無法顯示的情況進(jìn)行了優(yōu)化
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();
}
}