(转载)Unity3D开发之编辑器统一修改Text字体

最近遇到一个需求,就是我们在做完一个场景后,美工感觉字体不好看,效果不是很好,想要换一种字体。UGUI的界面已经搭完,如果要一个一个Text寻找,工作量将是巨大。而且作为程序人员是不会容忍自己做这些机械工作的,所以,有必要写一个脚本来让场景中的Text字体变换了。

 

using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.UI;

public class ChangeFontWindow : EditorWindow
{
    [MenuItem("Tools/更换字体")]
    public static void Open()
    {
        EditorWindow.GetWindow(typeof(ChangeFontWindow));
    }

    Font toChange;
    static Font toChangeFont;
    FontStyle toFontStyle;
    static FontStyle toChangeFontStyle;

    void OnGUI()
    {
        toChange = (Font)EditorGUILayout.ObjectField(toChange, typeof(Font), true, GUILayout.MinWidth(100f));
        toChangeFont = toChange;
        toFontStyle = (FontStyle)EditorGUILayout.EnumPopup(toFontStyle, GUILayout.MinWidth(100f));
        toChangeFontStyle = toFontStyle;
        if (GUILayout.Button("更换"))
        {
            Change();
        }
    }

    public static void Change()
    {
        Transform canvas = GameObject.Find("Canvas").transform;
        if (!canvas)
        {
            Debug.Log("NO Canvas");
            return;
        }
        Transform[] tArray = canvas.GetComponentsInChildren<Transform>();
        for (int i = 0; i < tArray.Length; i++)
        {
            Text t = tArray[i].GetComponent<Text>();
            if (t)
            {
                //这个很重要,博主发现如果没有这个代码,unity是不会察觉到编辑器有改动的,自然设置完后直接切换场景改变是不被保存
                //的  如果不加这个代码  在做完更改后 自己随便手动修改下场景里物体的状态 在保存就好了 
                Undo.RecordObject(t, t.gameObject.name);
                t.font = toChangeFont;
                t.fontStyle = toChangeFontStyle;
                //相当于让他刷新下 不然unity显示界面还不知道自己的东西被换掉了  还会呆呆的显示之前的东西
                EditorUtility.SetDirty(t);
            }
        }  
        Debug.Log("Succed");  
    }
}

希望本博客对你有帮助。

 

---------------------
作者:JayW就是我吖
来源:CSDN
原文:https://blog.csdn.net/qq_33994566/article/details/78325768

posted @ 2019-03-26 20:46  vuciao  阅读(5416)  评论(0编辑  收藏  举报