きゅぶろぐ

きゅぶんずの ぶろぐができて べんりだな

Unityで画面に描画せずにテキストの幅と高さを取る方法

var fontAsset = AssetDatabase.LoadAssetAtPath<Font>(fontPath);

var settings = new TextGenerationSettings
{
    generationExtents = Vector2.zero,
    textAnchor = TextAnchor.MiddleCenter,
    alignByGeometry = false,
    scaleFactor = 1.0f,
    color = Color.white,
    font = fontAsset,
    fontSize = Mathf.RoundToInt(fontSize),
    pivot = Vector2.zero,
    richText = false,
    lineSpacing = 0,
    fontStyle = FontStyle.Normal,
    resizeTextForBestFit = false,
    updateBounds = false,
    horizontalOverflow = HorizontalWrapMode.Overflow,
    verticalOverflow = VerticalWrapMode.Overflow
};

var textGenerator = new TextGenerator();
var width = textGenerator.GetPreferredWidth(rawText, settings);
var height = textGenerator.GetPreferredHeight(rawText, settings);