查找字符串在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;
}
相关推荐
霜绛1 天前
Unity:lua热更新(三)——Lua语法(续)
unity·游戏引擎·lua
世洋Blog1 天前
更好的利用ChatGPT进行项目的开发
人工智能·unity·chatgpt
evolution_language2 天前
Unity场景(Scene)的注意事项和易错点
unity·游戏引擎·scene
EQ-雪梨蛋花汤2 天前
【AI工具】使用 Doubao-Seed-Code 优化 Unity 编辑器插件:从功能实现到界面美化的完整实践
人工智能·unity·编辑器
Dr.勿忘2 天前
开源Unity小框架:高效单例与模块化设计
游戏·unity·开源·c#·游戏引擎·游戏程序·gamejam
jtymyxmz3 天前
《Unity Shader》8.4 透明度混合
unity·游戏引擎
世洋Blog4 天前
利用<<左移运算符优雅的设计游戏能力的任意组合和判断
游戏·unity·c#
毛甘木4 天前
Unity MonoPInvokeCallback 使用教程
c++·unity
心疼你的一切4 天前
Unity开发Rokid应用之离线语音指令交互模型
android·开发语言·unity·游戏引擎·交互·lucene
Sator14 天前
Unity使用OpenXR时,初始化失败的问题
unity·游戏引擎·vr