查找字符串在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;
}
相关推荐
WarPigs2 小时前
Unity性能优化笔记
笔记·unity·游戏引擎
T.D.C8 小时前
【业务框架】3C-相机-Cinemachine
unity
Clank的游戏栈19 小时前
Unity基于GraphView的可视化关卡编辑器开发指南
unity·编辑器·游戏引擎
海尔辛1 天前
Unity UI 性能优化--Sprite 篇
ui·unity·性能优化
XR-AI-JK2 天前
Unity VR/MR开发-VR设备与适用场景分析
unity·vr·mr
ChiLi_Lin2 天前
Unity异常上报飞书工具
unity·游戏引擎·飞书
地狱为王2 天前
基于VLC的Unity视频播放器(四)
unity·游戏引擎·音视频
2 天前
Unity与Excel表格交互热更方案
unity·游戏引擎·excel
装大炮的自行车3 天前
【Unity】R3 CSharp 响应式编程 - 使用篇(集合)(三)
windows·unity·游戏引擎
阿松爱学习3 天前
【Unity开发】控制手机移动端的震动
unity·游戏引擎·unity开发