jeromej
jeromej

Reputation: 11588

Unity load a font from the disk or the web

This font needs to be dynamically changed so I can't put it in Resources.

I haven't found any resources or way to achieve this, all talk about Resources.

EDIT: I did look into AssetBunble but it looked overkill so I thought maybe requiring the user to install the font on his machine but Font.CreateDynamicFontFromOSFont does nothing. Whatever the given input (even invalid), it will always return the same "Arial" font and nothing visually change.

I might look into AssetBundles again but I don't want Unity installed on the target machine and if I understood right, you can't build an assetbundle without running Unity.

Upvotes: 1

Views: 2530

Answers (1)

Programmer
Programmer

Reputation: 125255

There is no Unity API to load standard font from disk or web into Unity's Font.

If you use Font.CreateDynamicFontFromOSFont, the font must be installed on the device. This is easy to do on some platforms like Windows but extremely hard on devices like Android.


The recommended way to do this is to use AssetBundles. You will need the Unity Editor to create the AssetBundles but you don't need it to load the AssetBundles during run-time. Put the fonts in AssetBundles then build it and host it on the server. Use UnityWebRequest API to download the Assetbundle then extract the font from it. You can always update this Assetbundle on the server.

If you want the user to to able to load the font from any source, you can automate the building part by asking the user where the font is, take that font and send/upload it to your server with the UnityWebRequest API. On the server side, run Unity Editor in a headless mode, retrieve the font sent to it and build an Assetbundle from it then send it back to the player and load it on the client side.

So, UnityWebRequestAssetBundle.GetAssetBundle is used to download the AssetBundle and AssetBundle.LoadAssetAsync is used to the fonts in it.

There is no other way to do this unless you have the Unity source code which is really expensive. By doing it this way, you won't need the font to be installed and won't run into issues on mobile devices. This post shows how to build and load an Assetbundle but you have to do that in headless mode.

Upvotes: 2

Related Questions