查找字符串在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;
}
相关推荐
地狱为王19 小时前
Unity使用RVM实现实时人物视频抠像(无绿幕)
unity·游戏引擎·音视频
HahaGiver6661 天前
Unity与Android原生交互开发入门篇 - 打开Android的设置
android·java·unity·游戏引擎·android studio
野奔在山外的猫1 天前
【解决】解决方案内存在对应命名空间,但程序引用显示无该命名空间问题
unity
B0URNE1 天前
【Unity基础详解】(5)Unity核心:Coroutines协程
unity·游戏引擎
野奔在山外的猫1 天前
【案例】程序化脚本生成
unity
xiaotao1311 天前
unity hub在ubuntu 22.0.4上启动卡住
ubuntu·unity·游戏引擎
小句2 天前
通过图表和详细流程解释XXL-JOB中任务从创建到执行的完整过程
unity·游戏引擎
!chen2 天前
Unity颜色曲线ColorCurves
unity·游戏引擎
B0URNE2 天前
【Unity基础详解】(4)Unity核心类:MonoBehaviour
unity·游戏引擎
小时候的阳光3 天前
Cocos Creator 和 Unity 3D 编辑界面字体样式大小调整
unity·cocos2d·字体大小