Unity3D 统一修改Text的字体
前言
Unity3D中有时需要一下修改很多Text的字体,要是都一个一个去修改就太麻烦了,所以我们需要一个脚本来帮助我们完成。(在原文的基础上,我自己拓展了一下指定字体的修改。)
效果
代码
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class ChangeFontWindow : EditorWindow
{
[MenuItem("Tools/更换字体")]
public static void Open()
{
/*第一个参数窗口类型,决定窗口操作逻辑
* 第二个参数确定是否为浮动窗口,选择false可有停靠效果
* 第三个参数 显示窗口的标题
*/
EditorWindow.GetWindow(typeof(ChangeFontWindow), false,"更换字体");
}
bool SpecifyFontReplace;//指定字体更换
Font oldFont;
Font toChange;
static Font toChangeFont;
FontStyle toFontStyle;
static FontStyle toChangeFontStyle;
void OnGUI()
{
SpecifyFontReplace = EditorGUILayout.Toggle("指定字体更换:", SpecifyFontReplace);
if (SpecifyFontReplace)
oldFont = (Font)EditorGUILayout.ObjectField("需要改动的字体:", oldFont, typeof(Font), true, GUILayout.MinWidth(100f));
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 void Change()
{
//寻找Hierarchy面板下所有的Text
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 (SpecifyFontReplace)//指定字体更换,只更换某一种字体为目标字体
{
if (t.font == oldFont)
{
t.font = toChangeFont;
t.fontStyle = toChangeFontStyle;
}
}
else//更换所有字体为目标字体
{
t.font = toChangeFont;
t.fontStyle = toChangeFontStyle;
}
//相当于让他刷新下 不然unity显示界面还不知道自己的东西被换掉了 还会呆呆的显示之前的东西
EditorUtility.SetDirty(t);
}
Debug.Log("Succed");
}
}
END