Unity Editor批量修改Text的字体

更换预设中所有Text的字体,如果Text比较多的话一个个修改既繁琐废时间,而且可能改漏,写个小工具换字体就容易多了。

public class MyTools : EditorWindow
{
    static Object[] objs;
    static MyTools window;
    Font changeFont;

    private void OnGUI()
    {
        ChangeFont();
    }

    [MenuItem("Assets/MyTools/字体设置")]
    public static void InitFont()
    {
        objs = Selection.objects;
        if (objs != null && objs.Length > 0)
        {
            var prefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
            if (prefabStage == null)
            {
                Debug.LogError("先打开预设!!!");
                return;
            }
            else
            {
                if (!objs[0].name.Equals(prefabStage.prefabContentsRoot.name))
                {
                    Debug.LogError("请选择对应的预设!!!");
                    return;
                }
            }
            window = (MyTools)GetWindow(typeof(MyTools));
            window.titleContent.text = "字体设置";
            window.position = new Rect(PlayerSettings.defaultScreenWidth / 2, PlayerSettings.defaultScreenHeight / 2, 400, 160);
            window.Show();
        }
    }

    private void ChangeFont()
    {
        GUILayout.BeginVertical();
        GUILayout.Label("!!!需要先打开并选择对应的预设!!!");
        GUILayout.BeginHorizontal();
        GUILayout.Label("NewFont:");
        changeFont = (Font)EditorGUILayout.ObjectField(changeFont, typeof(Font), true, GUILayout.MinWidth(100f));
        GUILayout.EndHorizontal();
        if (GUILayout.Button("确认"))
        {
            var tArray = Resources.FindObjectsOfTypeAll(typeof(Text));
            for (int i = 0; i < tArray.Length; i++)
            {
                Text t = tArray[i] as Text;
                //提交修改,如果没有这个代码,unity不会察觉到编辑器有改动,同时改动也不会被保存
                Undo.RecordObject(t, t.gameObject.name);
                if (changeFont)
                    t.font = changeFont;
            }
            window.Close();
        }
        GUILayout.EndVertical();
    }
}

 

你可能感兴趣的:(Unity,Editor,unity,游戏引擎)