Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Question How to property implement nested sources inside custom formatters?

Discussion in 'Localization Tools' started by julcreutz, Jan 21, 2024.

  1. julcreutz

    julcreutz

    Joined:
    May 4, 2021
    Posts:
    21
    I have this Smart String that I want to format:
    {Highlighted:{CutLogCount}}

    The Highlighted source is a custom formatter that replaces it with a TextMeshPro text style, which in this case firstly evaluates the format to:
    <style=Highlighted>{CutLogCount}</style>

    I also want to format the CutLogCount variable though, which I add as a local variable of type int.
    Right now, I'm formatting the nested source like this, which is obviously hacky, but I haven't been able to implemented it "properly" using the provided API and the IFormattingInfo parameter.

    Any help would be greatly appreciated!

    Code (CSharp):
    1. [Serializable]
    2. [DisplayName("Text Style Formatter")]
    3. public sealed class TextStyleFormatter : FormatterBase
    4. {
    5.     private const string DefaultFormat = "<style={0}>{1}</style>";
    6.    
    7.     [SerializeField] private string _format = DefaultFormat;
    8.  
    9.     public override string[] DefaultNames => new[] { "" };
    10.    
    11.     public override bool TryEvaluateFormat(IFormattingInfo formattingInfo)
    12.     {
    13.         if (formattingInfo.CurrentValue is not TMP_Style style)
    14.         {
    15.             return false;
    16.         }
    17.  
    18.         var content = formattingInfo.Format.RawText;
    19.  
    20.         if (content.StartsWith("{") && content.EndsWith("}") && formattingInfo.FormatDetails.FormatCache.LocalVariables.TryGetValue(content[1..^1], out var variable))
    21.         {
    22.             content = variable.GetSourceValue(null).ToString();
    23.         }
    24.        
    25.         var text = string.Format(_format, style.name, content);
    26.        
    27.         formattingInfo.Write(text);
    28.        
    29.         return true;
    30.     }
    31. }
     
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,275
  3. julcreutz

    julcreutz

    Joined:
    May 4, 2021
    Posts:
    21
  4. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,275