using MiniJSON; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using TMPro; using UnityEngine; using UnityEngine.TextCore.LowLevel; public class TextMeshFontAssetManager : MonoSingleton<TextMeshFontAssetManager> { private Dictionary<string, TMP_FontAsset> AddFontWithPathList = new Dictionary<string, TMP_FontAsset>(); [DllImport("__Internal")] private static extern string __NT_GetSystemFonts(); public void AddFontAsset(ScriptableObject fontAsset) { if (CheckFontAsset(fontAsset)) return; var def = TMP_Settings.defaultFontAsset; def.fallbackFontAssetTable.Add(fontAsset as TMP_FontAsset); } public void RemoveFontAsset(ScriptableObject fontAsset) { if (!CheckFontAsset(fontAsset)) return; var def = TMP_Settings.defaultFontAsset; def.fallbackFontAssetTable.Remove(fontAsset as TMP_FontAsset); } public bool CheckFontAsset(ScriptableObject fontAsset) { TMP_FontAsset font = fontAsset as TMP_FontAsset; var def = TMP_Settings.defaultFontAsset; return def.fallbackFontAssetTable.Contains(font); } public void AddWithOSFont(List<string> tb) { //这里是获取到设备上的字体路径列表 提取名字把需要的动态添加 Dictionary<string, string> fontPaths = new Dictionary<string, string>(); IEnumerable tempPaths = null; #if UNITY_IPHONE && !UNITY_EDITOR //IOS的Font.GetPathsToOSFonts在2019.4.7之前获取的为空,所以写了个接口获取,接口内容在Unity/IOS笔记本 string jsonData = __NT_GetSystemFonts(); if (!string.IsNullOrEmpty(jsonData)) { tempPaths = Json.Deserialize(jsonData) as List<object>; } #else tempPaths = Font.GetPathsToOSFonts(); #endif if (tempPaths == null) return; foreach (string path in tempPaths) { string key = Path.GetFileNameWithoutExtension(path); if(!fontPaths.ContainsKey(key)) fontPaths.Add(key, path); } for (int i = 0; i < tb.Count; i++) { string fontname = tb[i]; if (fontPaths.ContainsKey(fontname)) { AddFontAssetByFontPath(fontPaths[fontname]); } } } //可以从网上下载字体或获取到本地自带字体 public void AddFontAssetByFontPath(string fontPath) { if (AddFontWithPathList.ContainsKey(fontPath)) return; Font font = new Font(fontPath); TMP_FontAsset tp_font = TMP_FontAsset.CreateFontAsset(font, 20, 2, GlyphRenderMode.SDFAA, 512, 512); AddFontAsset(tp_font); AddFontWithPathList.Add(fontPath, tp_font); } public void RemoveFontAssetByFontPath(string fontPath) { if (!AddFontWithPathList.ContainsKey(fontPath)) return; TMP_FontAsset tp_font = AddFontWithPathList[fontPath]; RemoveFontAsset(tp_font); } public int GetSystemLangeuage() { return (int)Application.systemLanguage; } }