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
相关推荐
mxwin11 小时前
Unity Shader 半透明物体为什么不能写入深度缓冲?晚枫歌F12 小时前
三层时间轮的实现咸鱼永不翻身14 小时前
Lua脚本事件检查工具leo__52015 小时前
单载波中继系统资源分配算法MATLAB仿真程序努力长头发的程序猿16 小时前
Unity使用ScriptableObject序列化资源mxwin17 小时前
Unity Shader 手写基于 PBR 的 URP Lit Shader 核心光照计算小贺儿开发17 小时前
Unity3D 智能云端数字标牌系统魔士于安17 小时前
Unity windows 同步 异步 打开文件文件夹工具魔士于安18 小时前
unity lowpoly 风格 城市 建筑 道路 交通标志mxwin18 小时前
Unity GPU Shader 性能优化指南