查找字符串在Text文本中的位置

复制代码
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;
}
相关推荐
Thomas_YXQ5 小时前
Unity3D IK解算器技术分析
开发语言·搜索引擎·unity·全文检索·unity3d·lucene
星火撩猿14 小时前
常见游戏引擎介绍与对比
unity·ue5·游戏引擎·godot
sky_smile_Allen14 小时前
[Unity]-[UI]-[Prefab] 关于Unity UGUI 的布局及组件讲解
ui·unity·游戏引擎
太妃糖耶20 小时前
URP-利用矩阵在Shader中实现物体的平移和缩放
unity·矩阵
是阿根1 天前
unity使用iTextSharp生成PDF文件
unity·c#·游戏引擎
常城2 天前
Unity中通过TMP使用图片字体
unity·游戏引擎
惊鸿醉2 天前
⭐Unity 开发 | 如何通过 NTP 网络时间实现精准的跨平台时间同步【附完整源码 + UI 模块 + 偏差分析】
网络·unity·游戏引擎
海鸥-w2 天前
Unity中使用Cinemachine插件创建自由视角相机(freelookCamera)来实现第三人称漫游
数码相机·unity·游戏引擎
EQ-雪梨蛋花汤2 天前
【Unity笔记】Unity音效管理:ScriptableObject配置 + 音量控制 + 编辑器预览播放自动化实现
笔记·unity·编辑器
qq_431331353 天前
Unity ML-Agents + VScode 环境搭建 Windows
windows·vscode·unity·强化学习