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 RPG 入门项目(四)背包拖拽、物品悬浮提示、项目开发思维xcLeigh18 小时前
Unity基础:Start与Update方法——Unity脚本生命周期初探郝学胜-神的一滴20 小时前
[简化版 GAMES 104] 现代游戏引擎 05:游戏引擎世界构建核心机制深度解析LONGZETECH2 天前
无人机实训高成本痛点解法:虚拟仿真实现 70% 耗材损耗下降五仁烧饼2 天前
Unity Addressables 静默资源策略fanfan_hongyun3 天前
unity 与cad 坐标系映射神码编程3 天前
【Unity】 HTFramework框架(七十)MultiChoiceDropdown可多选的下拉菜单淡海水3 天前
15-07-YooAsset面试篇-Unity性能优化与内存管理zhchyun20084 天前
# 【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(03)淡海水4 天前
15-02-YooAsset面试篇-Unity架构设计与源码