本文相较原文新增了尾引号(包括单引号和双引号)的检测,并修复了一个Substring参数错误的bug。
新建一个类继承Text,并将以下代码复制到里面去。
private readonly string markList = "(\!|\?|\,|\。|\《|\》|\)|\:|\“|\”|\‘|\’|\、|\;|\+|\-)";
StringBuilder textStr;
public override void SetVerticesDirty()
{
var settings = GetGenerationSettings(rectTransform.rect.size);
cachedTextGenerator.Populate(this.text, settings);
textStr = new StringBuilder(this.text);
IList<UILineInfo> lineList = this.cachedTextGenerator.lines;
int changeIndex = -1;
for (int i = 1; i < lineList.Count; i++)
{
bool isMark = Regex.IsMatch(text[lineList[i].startCharIdx].ToString(), markList);
if (isMark)
{
changeIndex = lineList[i].startCharIdx - 1;
int startIndex = lineList[i - 1].startCharIdx;
int endIndex = lineList[i].startCharIdx;
string str = text.Substring(startIndex, endIndex - startIndex);
MatchCollection richStrMatch = Regex.Matches(str, ".(</color>|<color=#\\w{6}>|" + markList + ")+$");
if (richStrMatch.Count > 0)
{
string richStr = richStrMatch[0].ToString();
int length = richStr.Length;
changeIndex = lineList[i].startCharIdx - length;
break;
}
}
}
if (changeIndex >= 0)
{
textStr.Insert(changeIndex, '\n');
this.text = textStr.ToString();
}
base.SetVerticesDirty();
}
原理
Text是继承Graphic的,所以在改变Text.text时,渲染会脏掉,此时重新渲染,在渲染之前进行正则表达式处理文字。
注意:
1.建议在想要处理标签枚举的前面都加上\,防止出现出现如+这样的正则表达式关键字导致代码报错。
2.使用StringBuilder,C#中不可修改String。
3.修改文字的textStr用全局变量,防止GC。