查找字符串在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;
}
相关推荐
qq 180809514 小时前
从零构建一个多目标多传感器融合跟踪器
unity
平行云5 小时前
实时云渲染支持在网页上运行UE5开发的3A大作Lyra项目
unity·云原生·ue5·webgl·虚拟现实·实时云渲染·像素流送
鹏飞于天5 小时前
Shader compiler initialization error: Failed to read D3DCompiler DLL file
unity
wonder135797 小时前
UGUI重建流程和优化
unity·游戏开发·ugui
那个村的李富贵11 小时前
Unity打包Webgl后 本地运行测试
unity·webgl
nnsix12 小时前
Unity OpenXR开发HTC Vive Cosmos
unity·游戏引擎
nnsix12 小时前
Unity OpenXR,扳机键交互UI时,必须按下扳机才触发
unity·游戏引擎
nnsix12 小时前
Unity XR 编辑器VR设备模拟功能
unity·编辑器·xr
老朱佩琪!12 小时前
Unity访问者模式
unity·游戏引擎·访问者模式
不定时总结的那啥13 小时前
Unity实现点击Console消息自动选中预制体的方法
unity·游戏引擎