查找字符串在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;
}
相关推荐
魔士于安9 小时前
unity 音乐会场景 unity2022
游戏·unity·游戏引擎·贴图·模型
Mediary11 小时前
Unity is running with Administrator privileges, which isnot supported...
unity
游乐码14 小时前
Unity基础(十四)场景异步加载
unity·游戏引擎
mxwin14 小时前
Unity Shader URP:法线在空间变换上的特殊性
unity·游戏引擎·shader
nnsix15 小时前
Unity 动态批处理、静态批处理、GPU Instaning、SRP Batcher 笔记
笔记·unity·单一职责原则
charlee4415 小时前
Unity在安卓端如何调试输出信息
android·unity·adb·游戏引擎·真机调试
_Athie17 小时前
【开发工具】自动创建项目文件夹结构
unity·编辑器
auccy1 天前
Unity Sprite 添加法线贴图
unity·贴图·normal
mxwin2 天前
次世代角色 PBR 贴图制作 + Unity URP 接入 极简流程图
unity·流程图·贴图·shader