很多时候我们在Unity做项目的时候用的是系统默认字体,当UI场景全部都搭完了之后觉得字体不大适合想更换,难道要一个一个的去更改UGUI上的字体吗?
作为一名开发人员这种复杂而又无脑的操作怎么可能自己一个一个弄?话不多说,直接上脚本
大致原理就是通过查找画布来自动替换字体,替换前请将需要替换的场景文字UI打开,此脚本不会更改SetActive(false)的物体组件,当然你也可以在项目运行时通过 Unity状态栏---Tools---更换字体 来使用
using UnityEngine;
using UnityEditor;
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)
{
//如果不加这个代码 在做完更改后 自己随便修改下场景里物体的状态 在保存就好了 ,不然他会觉得没变 就不会保存 就失败了
Undo.RecordObject(t, t.gameObject.name);
t.font = toChangeFont;
t.fontStyle = toChangeFontStyle;
//刷新下
EditorUtility.SetDirty(t);
}
}
Debug.Log("Succed");
}
}
有用的话建议收藏起来!