public static Vector3 GetStringPositionAtText(Text text, string strFragment)
{
int strFragmentIndex = text.text.IndexOf(strFragment); //-1表示不包含strFragment
Vector3 stringPos = Vector3.zero;
if (strFragmentIndex > -1)
{
Vector3 firstPos = GetCharPositionAtText(text, strFragmentIndex + 1);
Vector3 lastPos = GetCharPositionAtText(text, strFragmentIndex + strFragment.Length);
stringPos = (firstPos + lastPos) * 0.5f;
}
else
{
stringPos = GetCharPositionAtText(text, strFragmentIndex);
}
return stringPos;
}
public static Vector3 GetCharPositionAtText(Text text, int charIndex)
{
string textStr = text.text;
Vector3 charPos = Vector3.zero;
if (charIndex <= textStr.Length && charIndex > 0)
{
TextGenerator textGen = new TextGenerator(textStr.Length);
Vector2 extents = text.rectTransform.rect.size;
textGen.Populate(textStr, text.GetGenerationSettings(extents));
int newLine = textStr.Substring(0, charIndex).Split('\n').Length - 1;
int whiteSpace = textStr.Substring(0, charIndex).Split(' ').Length - 1;
int indexOfTextQuad = (charIndex * 4) + (newLine * 4) - 4;
if (indexOfTextQuad < textGen.vertexCount)
{
charPos = (textGen.verts[indexOfTextQuad].position +
textGen.verts[indexOfTextQuad + 1].position +
textGen.verts[indexOfTextQuad + 2].position +
textGen.verts[indexOfTextQuad + 3].position) / 4f;
}
}
charPos = text.transform.TransformPoint(charPos); //转换为世界坐标
return charPos;
}
查找字符串在Text文本中的位置
IT_yanghui2024-03-12 21:41
相关推荐
★YUI★4 小时前
学习游戏制作记录(克隆技能)7.25不绝1917 小时前
ARPG开发流程第一章——方法合集玩代码7 小时前
Unity里的加力贵州晓智信息科技8 小时前
Unity 性能优化全攻略UWA10 小时前
UWA DAY 2025 游戏开发者大会|全议程unicrom_深圳市由你创科技11 小时前
Unity 的UI动画调节咩咩觉主14 小时前
Unity编辑器拓展 IMGUI与部分Utility知识总结(代码+思维导图)龚子亦1 天前
【Unity开发】数据存储——XMLwrite_the_code1 天前
Unity国际版下载链接分享(非c1国内版)Bulling_1 天前
unity动态背景制作