コガネブログ

平日更新を目標に 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 );
    }
}

使用例

using TMPro;
using UnityEngine;

public class Example : MonoBehaviour
{
    public TMP_Text m_tmpText;

    private void Update()
    {
        var x = m_tmpText.GetLocalEdgeLeft();
        var y = m_tmpText.GetLocalEdgeBottom();

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