查找字符串在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;
}
相关推荐
死也不注释7 分钟前
【Unity UGUI 交互组件——Slider(7)】
unity·游戏引擎·交互
程序猿多布5 小时前
XLua教程之热补丁技术
unity·c#·lua·xlua
SmalBox8 小时前
【光照】Unity中的[光照模型]概念辨析
unity·渲染
挂科是不可能出现的9 小时前
unity导入blender动画
unity·游戏引擎·blender
派葛穆10 小时前
Unity-按钮实现场景跳转
java·unity·游戏引擎
程序猿多布12 小时前
XLua教程之Lua调用C#
unity·c#·lua·xlua
lrh30251 天前
Custom SRP - Point and Spot Lights
unity·srp·render pipeline
绀目澄清1 天前
unity UGUI 鼠标画线
unity·计算机外设·游戏引擎
作孽就得先起床1 天前
unity pcd 二进制版 简单显示文件对象(单色)
unity·游戏引擎
SmalBox1 天前
【光照】Unity[经验模型]和[物理模型]
unity·渲染