您的位置:首页 > 移动开发 > Unity3D

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

2017-10-24 09:17 537 查看
最近遇到一个需求,就是我们在做完一个场景后,美工感觉字体不好看,效果不是很好,想要换一种字体。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");
}
}希望本博客对你有帮助。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity3d 编辑器 字体