Importing external fonts at runtime and generating TMP_FontAssets

Hey guys, got a fun challenge for you: Trying to load an external font at runtime and creating a TMP_FontAsset with it. So far, this is my testing code:

var font = Font.CreateDynamicFontFromOSFont("8BIT Wonder", 14);
fontAsset = TMP_FontAsset.CreateFontAsset(font, 90, 0, UnityEngine.TextCore.LowLevel.GlyphRenderMode.SDFAA, 1024, 1024, AtlasPopulationMode.Dynamic);
fontAsset.name = "8BIT Wonder";
print(fontAsset.material); //for debugging, comes back as: TestMeshPro/Mobile/Distance Field (UnityEngine.Material)

GetComponent<TMP_Text>().font = fontAsset;

However, on-screen nothing changes font-wise, which makes me think the font creation didn’t work and it’s ‘falling back’ to the ‘fallback’ font. Also another thing that might be wrong is the material.
Usually TMP_FontAssets have their own ‘generated’ material but this one doesn’t. Any way to generate it?

I already asked this on the Unity Discord and someone else who tried running this code also pointed out that the font atlas is null.

I am sure that achieving this is possible, question is how.

var font = Font.CreateDynamicFontFromOSFont("8BIT Wonder", 14);

Does not actually create a valid font that TMP can use in the sense that it does not include the font file data.

Give the following a try as it should work on most platforms.

// Get the file path of all OS fonts.
string[] fontPaths = Font.GetPathsToOSFonts();

// Create new Font using one of those paths.
Font osFont = new Font(fontPaths[124]);

// Create new font asset using this OS font.
TMP_FontAsset fontAsset = TMP_FontAsset.CreateFontAsset(osFont);

By should work on most platform, the GetPathsToOSFonts() may fail to return a valid path for a font file. However, it you have a valid path to such font file, then creating a new font from it will work.

Ah, thanks! That worked :slight_smile:

For future visitors who may stumble upon this problem, solution is simple. Use new Font(...) rather than Font.CreateDynamicFontFromOSFont(...)

1 Like