Unity通过代码实现创建自定义字体
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
public class MyFont : MonoBehaviour
{
[MenuItem("Assets/CreateImageFont")]
private static void CreateImageFont()
{
if (Selection.objects.Length <= 0)
{
Debug.LogError("未选择图片!");
return;
}
Object[] objects = Selection.objects;
for (int i = 0; i < objects.Length; i++)
{
if (objects[i].GetType() == typeof(Texture2D))
{
CreateFont(objects[i] as Texture2D);
}
}
Debug.Log("创建字体成功!");
}
public static void CreateFont(Texture2D texture2D)
{
string texturePath = AssetDatabase.GetAssetPath(texture2D);
string extension = Path.GetExtension(texturePath);
string createPath = texturePath.Remove(texturePath.Length-extension.Length);
string fontPath = createPath + ".fontsettings";
Font font = AssetDatabase.LoadAssetAtPath<Font>(fontPath);
if (font == null)
{
font = new Font();
Material material = new Material(Shader.Find("GUI/Text Shader"));
material.mainTexture = texture2D;
string matPath = createPath + ".mat";
AssetDatabase.CreateAsset(material, matPath);
font.material = material;
AssetDatabase.CreateAsset(font, fontPath);
}
Sprite[] sprites = GetAllSelectSprite(texturePath);
CharacterInfo[] characterInfos = new CharacterInfo[sprites.Length];
for (int i = 0; i < characterInfos.Length; i++)
{
characterInfos[i] = new CharacterInfo();
Rect rect = sprites[i].rect;
characterInfos[i].index = sprites[i].name[sprites[i].name.Length-1];
characterInfos[i].uvBottomLeft = new Vector2(rect.x/texture2D.width,rect.y/texture2D.height);
characterInfos[i].uvBottomRight = new Vector2((rect.x+rect.width)/texture2D.width,rect.y/texture2D.height);
characterInfos[i].uvTopLeft = new Vector2(rect.x/texture2D.width,(rect.y+rect.height)/texture2D.height);
characterInfos[i].uvTopRight = new Vector2((rect.x+rect.width)/texture2D.width,(rect.y+rect.height)/texture2D.height);
characterInfos[i].minX = 0;
characterInfos[i].maxX = (int)rect.width;
characterInfos[i].minY = 0 - (int)sprites[i].pivot.y;
characterInfos[i].maxY = (int)rect.height - (int)sprites[i].pivot.y;
characterInfos[i].advance = (int)rect.width;
}
font.characterInfo = characterInfos;
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
EditorUtility.SetDirty(font);
}
private static Sprite[] GetAllSelectSprite(string path)
{
List<Sprite> sprites = new List<Sprite>();
UnityEngine.Object[] objects = AssetDatabase.LoadAllAssetsAtPath(path);
if (objects.Length <= 0)
{
Debug.LogError("请切割图片!");
}
for (int i = 0; i < objects.Length; i++)
{
if (objects[i].GetType() == typeof(Sprite))
{
sprites.Add(objects[i] as Sprite);
}
}
return sprites.ToArray();
}
}