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
相关推荐
流浪打工人14 小时前
Unity3d TimeLine中audio track的使用淡海水16 小时前
02-07-原理篇-GC暂停时间的本质WarPigs16 小时前
UI路径配置SO>字典json工作流淡海水20 小时前
02-06-原理篇-增量式GC与并发GC阿松爱学习1 天前
【Unity开发】Aspose.PDF的使用淡海水1 天前
02-04-原理篇-GC Roots与对象图遍历Martina_03216 天前
AI生成3D场景导入 Unity/Unreal 后,NPC 总串层?用6步检查导航高度与跨层连接小贺儿开发6 天前
Unity 局域网遥控幻灯片展示工具 3.0WarPigs8 天前
Unity对象不应该使用null传播的问题每日出拳老爷子9 天前
【VR】【Unity】抓走转放系列21|一天搭完门和抽屉工具槽:小场景按这个次序拼装