如何在运行时加载平台特定字体

How to load platform specific fonts at runtime

我正在尝试让应用程序根据平台设置一些资产。

第一步是让字体基于 OS,Roboto 用于 Android,SanFrancisco 用于 iOS。

简单的说,Unity在运行的时候是不能导入字体的,相对于其他跨平台IDE来说还是有点小缺点的,不过这里不做评判。另一种解决方案是使用 AssetBundle,由于无法解释的原因,它对我来说无法正常工作...

最重要的是,人们并未普遍认为将字体等基本资产存储为字体以外的东西。

所以我的最终解决方案是这个丑陋的脚本:

class FontFamily
{
     [Header("Android")]
     [SerializeField]
     private Font regularAndroid = null;
     [SerializeField]
     private Font boldAndroid = null;
     [SerializeField]
     private Font italicAndroid = null;
     [Header("iOS")]
     [SerializeField]
     private Font regularIOS = null;
     [SerializeField]
     private Font boldIOS = null;
     [SerializeField]
     private Font italicIOS = null;
     public Font Regular
     {
         get
         {
 #if UNITY_ANDROID
             return this.regularAndroid;
 #elif UNITY_IOS
             return this.regularIOS;
 #endif
         }
     }
     public Font Bold
     {
         get
         {
 #if UNITY_ANDROID
             return this.boldAndroid;
 #elif UNITY_IOS
             return this.boldIOS;
 #endif
         }
     }
     public Font Italic
     {
         get
         {
 #if UNITY_ANDROID
             return this.italicAndroid;
 #elif UNITY_IOS
             return this.italicIOS;
 #endif
         }
     }
 }

只是在寻找改进方法,因为从长远来看 运行 这不是一个可行的解决方案。我什至不能在参考上使用宏,因为它们在切换时会丢失。

我在想一些预构建脚本,基本上,你是怎么做到的?

实际上,Unity 可以在运行时导入字体而不使用 AB,但只能通过 Font.CreateDynamicFontFromOSFont.

导入 OS 的字体

非常简单的脚本,可在 Android 和旧金山在 iOS 中加载 Roboto 字体:

using UnityEngine;

public class LoadFontFromOS : MonoBehaviour {

    const string ANDROID_FONT_NAME = "Roboto";
    const string IOS_FONT_NAME = "SanFrancisco";

    string[] OSFonts;
    static Font selectedFont;
    public static Font SelectedFont {
        get {
            return selectedFont;
        }
    }
    static bool isFontFound;
    public static bool IsFontFound {
        get {
            return isFontFound;
        }
    }

    private void Awake() {
        isFontFound = false;
        OSFonts = Font.GetOSInstalledFontNames();
        foreach (var font in OSFonts) {
#if UNITY_ANDROID
            if (font == ANDROID_FONT_NAME) {
                selectedFont = Font.CreateDynamicFontFromOSFont(ANDROID_FONT_NAME, 1);
                isFontFound = true;
            }
#elif UNITY_IOS
            if (font == IOS_FONT_NAME) {
                selectedFont = Font.CreateDynamicFontFromOSFont(IOS_FONT_NAME, 1);
                isFontFound = true;
            }
#endif
        }
    }
}

然后您可以使用简单的

更改所有Text类型的字体
text.font = LoadFontFromOS.IsFontFound ? LoadFontFromOS.SelectedFont : text.font;

需要的地方。

我在 Android 上测试过它,它可以工作,我没有 iOS 设备来测试它,但它应该可以正常工作。