天天看點

Unity一鍵修改NGUI字型的編輯器腳本

第一次寫,目的就在于害怕以後忘了(尴尬),是以當筆記記下來,要是有些不對、不好、不規範的地方,希望幫忙指出來,我也能多學到一點東西。項目用的NGUI,要是UGUI稍微改動一下也能用,上代碼:

using UnityEngine;
using UnityEditor;

/// <summary>
/// 根據滑鼠點中的對象批量修改所有UI字型腳本,腳本位于Editor檔案夾
/// </summary>
public class ChangeFontWindow : EditorWindow
{
    //是否改變目前字型
    private static bool isChangFont = false;

    //目前字型
    private static Font curFont;

    //是否改變字型類型
    private static bool isChangeStyle = false;

    //字型類型
    private static FontStyle curFontStyle;

    //是否增加字型大小
    private static bool isExpandSize = false;

    //字型大小增加的值
    private static int fontSizeDelta = ;

    //window菜單下
    [MenuItem("Window/Change Font")]
    private static void ShowWindow()
    {
        ChangeFontWindow cw = GetWindow<ChangeFontWindow>(true, "修改字型");
        //(強迫症,看着舒服)
        cw.minSize = new Vector2(, );
        cw.maxSize = new Vector2(, );
    }

    private void OnGUI()
    {
        //向下空出5個像素
        GUILayout.Space();

        //建立是否改變目前字型開關
        isChangFont = EditorGUILayout.Toggle("是否改變目前字型", isChangFont);
        GUILayout.Space();

        //如果改變目前字型則建立字型檔案選擇框
        if(isChangFont)
        {
            curFont = (Font)EditorGUILayout.ObjectField("目标字型", curFont, typeof(Font), true);
            GUILayout.Space();
        }

        //建立是否改變字型類型開關
        isChangeStyle = EditorGUILayout.Toggle("是否改變字型類型", isChangeStyle);
        GUILayout.Space();

        //如果改變,則建立字型類型的枚舉下拉框
        if(isChangeStyle)
        {
            curFontStyle = (FontStyle)EditorGUILayout.EnumPopup("字型類型", curFontStyle);
            GUILayout.Space();
        }

        //建立是否增加字型大小的開關
        isExpandSize = EditorGUILayout.Toggle("是否增加字型大小", isExpandSize);
        GUILayout.Space();

        //如果增加字型大小則建立增加字型大小值的滑條
        if(isExpandSize)
        {
            fontSizeDelta = (int)EditorGUILayout.Slider("增加字型大小的值", fontSizeDelta, -, );
            GUILayout.Space();
        }

        //建立确認按鈕
        if(GUILayout.Button("确認修改", GUILayout.Height(), GUILayout.Width()))
        {
            Change();
        }
    }

    public static void Change()
    {
        //如果滑鼠沒有選中物體則傳回
        if(Selection.objects == null || Selection.objects.Length == ) { return; }

        //擷取點中對象(包括子目錄)所有UILabel元件
        Object[] labels = Selection.GetFiltered(typeof(UILabel), SelectionMode.Deep);

        //指派
        foreach(Object item in labels)
        {
            UILabel label = (UILabel)item;

            if(isChangFont) { label.trueTypeFont = curFont; }

            if(isChangeStyle) { label.fontStyle = curFontStyle; }

            if(isExpandSize) { label.fontSize += fontSizeDelta; }

            EditorUtility.SetDirty(item); //重要(有點像應用設定的意思)
        }
    }
}
           

搞定收工,根據需求再添加一下要修改的其他屬性也可以