docs.unity3d.com
    目次を表示する/隠す

    カスタムフォーマッターの作成

    カスタムフォーマッターは、FormatterBase クラスから継承して作成できます。

    カスタムフォーマッターを使用するには、Localization Settings 内で、それを Formatters リストに追加してください。

    この例は、バイトを表す整数を書式設定するフォーマッターの作成方法を示しています。

    using UnityEngine.Localization;
    using UnityEngine.Localization.SmartFormat.Core.Extensions;
    
    [DisplayName("Base 2 Byte Formatter")]
    public class ByteFormatter : FormatterBase
    {
        public override string[] DefaultNames => new string[] { "byte" };
    
        public override bool TryEvaluateFormat(IFormattingInfo formattingInfo)
        {
            if (formattingInfo.CurrentValue is long bytes)
            {
                // We are performing a Base 2 conversion here. 1024 bytes = 1 KB
                if (bytes < 512)
                {
                    formattingInfo.Write($"{bytes} B");
                    return true;
                }
    
                if (bytes < 512 * 1024)
                {
                    var kb = bytes / 1024.0f;
                    formattingInfo.Write($"{kb.ToString("0.00")} KB");
                    return true;
                }
    
                bytes /= 1024;
                if (bytes < 512 * 1024)
                {
                    var mb = bytes / 1024.0f;
                    formattingInfo.Write($"{mb.ToString("0.00")} MB");
                    return true;
                }
    
                bytes /= 1024;
                var gb = bytes / 1024.0f;
                formattingInfo.Write($"{gb.ToString("0.00")} GB");
                return true;
            }
    
            return false;
        }
    }
    
    Smart String の例 引数 結果
    The file size is {0:byte()} 100 The file size is 100 B
    1000 The file size is 0.98 KB
    1234 The file size is 1.21 KB
    10000000 The file size is 9.5 MB
    2000000000 The file size is 1.9 GB
    トップに戻る
    Copyright © 2023 Unity Technologies — 商標と利用規約
    • 法律関連
    • プライバシーポリシー
    • クッキー
    • 私の個人情報を販売または共有しない
    • Your Privacy Choices (Cookie Settings)