1. 程式人生 > >Unity用指令碼配置簡單的數字藝術字體CustomFont

Unity用指令碼配置簡單的數字藝術字體CustomFont

unity 2017.4.3f1
1、程式碼

/***************************************************
 * 檔名: FontCustom.cs
 * 時  間: 2018-10-30
 * 作  者: AnyuanLzh
 * 描  述: 
 ***************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class FontCustom
{
    static string fontPath = "Assets/AllRes/assetbundle/games/common/fonts/digit1.fontsettings";
    static string targetString = "0123456789x+.-";
    static int texWidth = 336;
    static int texHeight = 36;

    static int padding = -2;

    [MenuItem("Tools/Lzh/生成數字字型")]
    public static void GetAllFileNameInOneDir()
    {
        //Debug.LogError("使用前請在程式碼中設定好配置:" + fontPath);
        //return;


        Debug.Log("字型檔案不存在:" + fontPath);
        Font font = AssetDatabase.LoadAssetAtPath<Font>(fontPath);
        Debug.Log(font.name);
        if (font == null)
        {
            Debug.LogError("字型檔案不存在:"+ fontPath);
            return;
        }

        int num = targetString.Length;
        int fontWidth = texWidth / num;
        int fontHeight = texHeight;
        float uvWidth = 1f / num;
        List<CharacterInfo> charInfoList = new List<CharacterInfo>();
        for(int i=0; i<num; i++)
        {
            CharacterInfo charInfo = new CharacterInfo();
            charInfo.index = (int)targetString[i];
            charInfo.uvBottomLeft= new Vector2(uvWidth * i, 0);
            charInfo.uvBottomRight = new Vector2(uvWidth * i + uvWidth, 0);
            charInfo.uvTopLeft = new Vector2(uvWidth * i, 1);
            charInfo.uvTopRight = new Vector2(uvWidth * i + uvWidth, 1);
            charInfo.minX = 0;
            charInfo.maxX = fontWidth - 0;
            charInfo.minY = 0;
            charInfo.maxY = fontHeight;
             charInfo.advance = fontWidth + padding;
            if (targetString[i] == '.')
            {
                charInfo.advance = (fontWidth + padding)-(int)(fontWidth*0.3f);
            }
            else if(targetString[i] == '1')
            {
                charInfo.advance = (fontWidth + padding) - (int)(fontWidth * 0.1f);
            }

            charInfoList.Add(charInfo);
        }
        font.characterInfo = charInfoList.ToArray();
        EditorUtility.SetDirty(font);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }

}

2、效果
在這裡插入圖片描述

在這裡插入圖片描述