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
相关推荐
在路上看风景2 天前
1.2 Unity资源分类one named slash2 天前
BMFont在Unity中生成艺术字郝学胜-神的一滴2 天前
图形学中的纹理映射问题:摩尔纹与毛刺的深度解析在路上看风景2 天前
10. CPU-GPU协作渲染程序员agions2 天前
Unity 游戏开发邪修秘籍:从入门到被策划追杀的艺术JIes__2 天前
Unity(一)——场景切换、退出游戏、鼠标隐藏锁定...NIKITAshao2 天前
Unity URP Volume组件详解(笔记)lingxiao168882 天前
WebApi详解+Unity注入--下篇:Unity注入世洋Blog2 天前
面经-CPU、内存、GPU的性能优化lingxiao168882 天前
WebApi详解+Unity注入--中篇:.net core的WebAPI