查找字符串在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;
}
相关推荐
斯幽柏雷科技13 小时前
[Unity]Inspector各种写法(持续更新中)
java·unity·游戏引擎
毕竟秋山澪14 小时前
unity Skill接入TraeAI操作步骤
unity·游戏引擎
XR-AI-JK14 小时前
01-VR开发如何配置和搭建基础环境
unity·vr·vr基础教程·vr教程·vr实战教程·vr节奏游戏·unityvr教程
派葛穆14 小时前
Unity-生成预制体1
unity
WarPigs16 小时前
Unity CG着色器实战
unity·着色器
废嘉在线抓狂.17 小时前
TimeLine如何自定义轨道
unity·c#·对话系统
ellis19701 天前
Unity资源管理框架Addressables[六] 内存管理
unity
派葛穆1 天前
Unity-鼠标悬停改变物体层级
unity·游戏引擎
小贺儿开发2 天前
Unity3D 爆炸图案例演示
unity·产品·urp·机械拆装·爆炸图·零件·效果设计
Yasin Chen2 天前
Unity TMP_SDF 分析(二)数据来源2
unity·游戏引擎