Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Create TMPro Font asset at runtime

Discussion in 'UGUI & TextMesh Pro' started by LDawson97, Jun 6, 2021.

  1. LDawson97

    LDawson97

    Joined:
    Aug 16, 2018
    Posts:
    20
    Hi,

    I am looking to use the OS font for different devices and I'm struggling to understand how I can convert the Font data type into a TMPFont_Asset which I can assign to a TextMeshProUGUI field at runtime.

    The font can only be retrieved at runtime and so I cannot pre-create the fonts using tmp's font creator tools.

    I have this so far:
    Code (CSharp):
    1.  
    2. private void Awake()
    3.     {
    4.         string[] systemFontNames = Font.GetOSInstalledFontNames();
    5.  
    6.         // Find the Roboto Font
    7.         string fontName = "Roboto";
    8.  
    9.         foreach (string font in systemFontNames)
    10.         {
    11.             if (font.Contains(fontName))
    12.             {
    13.                 fontName = font;
    14.                 break;
    15.             }
    16.         }
    17.  
    18.         Font systemFont = Font.CreateDynamicFontFromOSFont(fontName, 36);
    19.  
    20.         //MenuManager.instance.settingPanelTitle.font = systemFont;
    21.     }
    22.  
    Thanks!
     
  2. Stephan_B

    Stephan_B

    Joined:
    Feb 26, 2017
    Posts:
    6,596
    There are a few posts about this already. Here is one of those posts / threads.

    Code (csharp):
    1.  
    2. // Get paths to OS Fonts
    3. string[] fontPaths = Font.GetPathsToOSFonts();
    4.  
    5. // Create new font object from one of those paths
    6. Font osFont = new Font(fontPaths[index]);
    7.  
    8. // Create new dynamic font asset
    9. TMP_FontAsset fontAsset = TMP_FontAsset.CreateFontAsset(osFont);
    Having said that, Dynamic OS Font Asset support is coming which will make this process even easier. The post linked above also contains information about that.