查找字符串在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;
}
相关推荐
浅陌sss12 小时前
Unity中可靠的UDP实现
unity
奔跑的犀牛先生18 小时前
unity学习46:反向动力学IK
unity
幻世界20 小时前
【工具插件类教学】实现运行时2D物体交互的利器Runtime2DTransformInteractor
unity·交互·运行时2d物体交互
音视频牛哥2 天前
Unity实现高性能多实例RTSP|RTMP播放器技术实践
unity·游戏引擎·音视频·实时音视频·大牛直播sdk·rtsp播放器·rtsp player
Artistation Game2 天前
三、Unity基础(主要框架)
游戏·unity·c#·游戏引擎
Edision_li2 天前
DeepSeek教unity------MessagePack-03
unity·messagepack
lalapanda2 天前
Unity学习part2
学习·unity·游戏引擎
CODE_RabbitV2 天前
【快速入门】Unity 常用组件(功能块)
unity·游戏引擎
BuHuaX2 天前
Unity-New Input System
unity·c#·游戏引擎·游戏程序·lucene
Edision_li3 天前
DeepSeek教unity------UI框架
学习·ui·unity·c#