コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】TextMesh Pro のワールド座標における端の位置を取得できる拡張メソッド

ソースコード

using System.Linq;
using TMPro;

public static class TMP_TextExtensionMethods
{
    public static float GetLocalEdgeLeft( this TMP_Text self )
    {
        return self.transform.localPosition.x + self.textInfo.characterInfo.Min( x => x.bottomLeft.x );
    }

    public static float GetLocalEdgeBottom( this TMP_Text self )
    {
        return self.transform.localPosition.y + self.textInfo.characterInfo.Min( x => x.bottomLeft.y );
    }

    public static float GetLocalEdgeRight( this TMP_Text self )
    {
        return self.transform.localPosition.x + self.textInfo.characterInfo.Max( x => x.topRight.x );
    }

    public static float GetLocalEdgeTop( this TMP_Text self )
    {
        return self.transform.localPosition.y + self.textInfo.characterInfo.Max( x => x.topRight.y );
    }

    public static float GetEdgeLeft( this TMP_Text self )
    {
        return self.transform.TransformPoint( self.textInfo.characterInfo.Min( x => x.bottomLeft.x ), 0, 0 ).x;
    }

    public static float GetEdgeBottom( this TMP_Text self )
    {
        return self.transform.TransformPoint( 0, self.textInfo.characterInfo.Min( x => x.bottomLeft.y ), 0 ).y;
    }

    public static float GetEdgeRight( this TMP_Text self )
    {
        return self.transform.TransformPoint( self.textInfo.characterInfo.Max( x => x.topRight.x ), 0, 0 ).x;
    }

    public static float GetEdgeTop( this TMP_Text self )
    {
        return self.transform.TransformPoint( 0, self.textInfo.characterInfo.Max( x => x.topRight.y ), 0 ).y;
    }
}

使用例

using TMPro;
using UnityEngine;

public class Example : MonoBehaviour
{
    public TMP_Text m_tmpText;

    private void Update()
    {
        var x = m_tmpText.GetEdgeLeft();
        var y = m_tmpText.GetEdgeBottom();

        transform.position = new( x, y );
    }
}