Unity3D开发之编辑器统一修改Text字体

来源:互联网 发布:遗传算法密码学 编辑:程序博客网 时间:2024/06/05 14:59

最近遇到一个需求,就是我们在做完一个场景后,美工感觉字体不好看,效果不是很好,想要换一种字体。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");      }}
希望本博客对你有帮助。

原创粉丝点击