自动化游戏框架工具集——艺术字生成工具 支持TextMeshPro/uGUI Text
艺术字在游戏中很常用,由于普通字体样式过于平淡,制作花里胡哨的文字图片作为游戏字体使用,这就是艺术字。
不依赖第三方工具,仅使用Unity自带的Custom Font + 一张艺术字图集就能实现这个功能,但是为了便于使用,还需要依赖自动化工具,自动化把字符映射到图片纹理坐标,一键生成字体文件。
当然,工具也必须支持生成TextMeshPro的TM_FontAsset;
工具使用效果:
字符对齐图片:
艺术字使用效果:
Unity自定义字体参数面板如下:
其中Character Rects数组是每个字符所在贴图的uv坐标系下的映射Rect:
Index:字符的Ascii码偏移值;字符真实ASCII码 = Ascii Start Offset + Index;这里建议把ASCII码起始值(Ascii Start Offset)设为0,把Index直接设置为字符的ASCII码。
Vert:字符的宽高信息, Y为高度的一半是为了垂直方向居中;
工具功能设计:
0. 首先,制作字符集图片,在Unity中用Sprite Editor进行自动Sprite碎图分割;
1. 拖拽添加字符图集;
2. 设置字符文件或直接在输入框输入字符,两处字符将自动合并去重;
3. 支持设置字体大小;自定义字体无法通过Text组件动态修改字体大小,因此需要为不同字号生成单独的字体文件,但材质和贴图共用,只消耗一个DC;
4.支持字符与图集对照预览;
5. 点击生成,一键创建字体文件和对应材质;
代码实现:
代码实现非常简单,主要就是读取Sprite中的子图Rect信息,然后转换到字体所需的UV坐标系Rect等;
使用Unity 2022新版Sprite编辑器API读取碎图信息:
var texFact = new SpriteDataProviderFactories();
texFact.Init();
var texDataProvider = texFact.GetSpriteEditorDataProviderFromObject(texture2d);
texDataProvider.InitSpriteEditorDataProvider();
var spriteRects = texDataProvider.GetSpriteRects();
生成字体文件的Character Rects:
private bool ParseCharsInfo(char[] chars, out CharacterInfo[] charInfoArr, out Texture2D charsTexture)
{
charInfoArr = null;
charsTexture = null;
if (chars == null || chars.Length < 1)
{
return false;
}
charsTexture = OwnerEditor.SelectObjectList[0] as Texture2D;
var texSize = new Vector2Int(charsTexture.width, charsTexture.height);
var texFact = new SpriteDataProviderFactories();
texFact.Init();
var texDataProvider = texFact.GetSpriteEditorDataProviderFromObject(charsTexture);
texDataProvider.InitSpriteEditorDataProvider();
var spRects = texDataProvider.GetSpriteRects();
int count = Mathf.Min(chars.Length, spRects.Length);
charInfoArr = new CharacterInfo[count];
for (int i = 0; i < count; i++)
{
var spRect = spRects[i].rect;
var uvMin = spRect.min / texSize;
var uvMax = spRect.max / texSize;
float fontHeight = m_FontSize;
float fontScale = m_FontSize / spRect.height;
charInfoArr[i] = new CharacterInfo
{
index = chars[i],
uvBottomLeft = uvMin,
uvBottomRight = new Vector2(uvMax.x, uvMin.y),
uvTopLeft = new Vector2(uvMin.x, uvMax.y),
uvTopRight = uvMax,
minX = 0,
minY = -(int)(fontHeight * 0.5f),//居中偏移量
advance = (int)(spRect.width * fontScale),
glyphWidth = (int)(spRect.width * fontScale),
glyphHeight = (int)fontHeight,
};
}
return true;
}
生成字体文件:
string outputDir = EditorUtility.SaveFolderPanel("保存到", Application.dataPath, null);
if (!string.IsNullOrWhiteSpace(outputDir) && Directory.Exists(outputDir))
{
outputDir = Path.Combine("Assets", Path.GetRelativePath(Application.dataPath, outputDir));
string outputFont = Path.Combine(outputDir, $"{charsTexture.name}_{m_FontSize}.fontsettings");
Font newFont;
if (!File.Exists(outputFont))
{
newFont = new Font(charsTexture.name);
AssetDatabase.CreateAsset(newFont, outputFont);
}
newFont = AssetDatabase.LoadAssetAtPath<Font>(outputFont);
string outputFontMat = Path.Combine(outputDir, $"{charsTexture.name}.mat");
if (!File.Exists(outputFontMat))
{
var tempFontMat = new Material(Shader.Find("UI/Default Font"));
AssetDatabase.CreateAsset(tempFontMat, outputFontMat);
}
var fontMat = AssetDatabase.LoadAssetAtPath<Material>(outputFontMat);
fontMat.shader = Shader.Find("UI/Default Font");
fontMat.SetTexture("_MainTex", charsTexture);
EditorUtility.SetDirty(fontMat);
AssetDatabase.SaveAssetIfDirty(fontMat);
newFont.material = fontMat;
newFont.characterInfo = charInfoArr;
EditorUtility.SetDirty(newFont);
AssetDatabase.SaveAssetIfDirty(newFont);
Selection.activeInstanceID = newFont.GetInstanceID();
}
生成TextMeshPro艺术字:
上述步骤中已经将文字图片图集解析为CharacterInfo,那么我们只需要稍加转换,把CharacterInfo转换为TextMeshPro的Glyph, 也就是字符与图集的uv映射关系:
private UnityEngine.TextCore.Glyph CharacterInfo2Glyph(int i, CharacterInfo charInfo, int atlasWidth, int atlasHeight)
{
var glyph = new UnityEngine.TextCore.Glyph((uint)i, new UnityEngine.TextCore.GlyphMetrics(charInfo.glyphWidth, charInfo.glyphHeight, 0, charInfo.glyphHeight, charInfo.glyphWidth),
new UnityEngine.TextCore.GlyphRect((int)(charInfo.uvBottomLeft.x * atlasWidth), (int)(charInfo.uvBottomLeft.y * atlasHeight), charInfo.glyphWidth, charInfo.glyphHeight));
return glyph;
}
然后动态创建一个TM_FontAsset并自动映射字符和图像:
private void GenerateTextMeshProFont(CharacterInfo[] charInfoArr, Texture2D charsTexture, string outputFont)
{
var maxHeight = charInfoArr[0].size;
var fontAsset = TMP_FontAsset.CreateFontAsset(m_TMPBaseFont, maxHeight, 0, UnityEngine.TextCore.LowLevel.GlyphRenderMode.SMOOTH, charsTexture.width, charsTexture.height, AtlasPopulationMode.Static, false);
AssetDatabase.CreateAsset(fontAsset, outputFont);
var tmpMat = new Material(Shader.Find("TextMeshPro/Bitmap Custom Atlas"));
var charsAtlas = UnityEngine.Object.Instantiate<Texture2D>(charsTexture);
charsAtlas.alphaIsTransparency = true;
var fileName = Path.GetFileNameWithoutExtension(outputFont);
tmpMat.name = Utility.Text.Format("{0}_mat", fileName);
tmpMat.mainTexture = charsAtlas;
charsAtlas.name = Utility.Text.Format("{0}_tex", fileName);
fontAsset.atlas = charsAtlas;
fontAsset.material = tmpMat;
fontAsset.atlasTextures = new Texture2D[] { charsAtlas };
fontAsset.characterTable.Clear();
fontAsset.glyphTable.Clear();
for (int i = 0; i < charInfoArr.Length; i++)
{
var charInfo = charInfoArr[i];
var glyph = CharacterInfo2Glyph(i, charInfo, charsAtlas.width, charsAtlas.height);
fontAsset.characterTable.Add(new TMP_Character((uint)charInfo.index, glyph));
fontAsset.glyphTable.Add(glyph);
}
var faceInfo = fontAsset.faceInfo;
faceInfo.familyName = fileName;
faceInfo.lineHeight = faceInfo.ascentLine = maxHeight;
faceInfo.baseline = faceInfo.descentLine = 0;
fontAsset.faceInfo = faceInfo;
var fontSettings = fontAsset.creationSettings;
fontSettings.referencedFontAssetGUID = null;
fontSettings.sourceFontFileGUID = null;
fontSettings.sourceFontFileName = null;
AssetDatabase.AddObjectToAsset(charsAtlas, fontAsset);
AssetDatabase.AddObjectToAsset(tmpMat, fontAsset);
EditorUtility.SetDirty(fontAsset);
AssetDatabase.SaveAssetIfDirty(fontAsset);
Selection.activeInstanceID = fontAsset.GetInstanceID();
}