using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Experimental.GraphView;
/// <summary>
/// UI替换字体
/// </summary>
public class UIFontEditor : EditorWindow
{
private static Font newFont;
private static string uiPrefabsDir = "Assets/RawAssets/UI";
private static int fontSizeOffset = 0;
private static bool isFontSize=false;
private static bool isFontBold=false;
[MenuItem("Tools/UI/UI字体替换")]
public static void CreateWindow()
{
GetWindow<UIFontEditor>("Change UI Font");
}
private void OnGUI()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginVertical();
EditorGUILayout.LabelField("该工具替换UI预设UILabel字体");
EditorGUILayout.LabelField("默认不改变字体大小和样式");
EditorGUILayout.LabelField("默认 UI Prefabs 路径:",uiPrefabsDir);
EditorGUILayout.Space(10);
uiPrefabsDir = EditorGUILayout.TextField("UI Prefabs Path:", uiPrefabsDir);
EditorGUILayout.Space(10);
newFont = EditorGUILayout.ObjectField("New Font", newFont, typeof(Font), false) as Font;
EditorGUILayout.Space(10);
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button(" - ",GUILayout.Width(50),GUILayout.Height(25)))
{
fontSizeOffset -= 2;
//if (fontSizeOffset < 0) fontSizeOffset = 0;
}
GUILayout.Label("字体size增加值:");
GUILayout.Label(fontSizeOffset.ToString());
if (GUILayout.Button(" + ",GUILayout.Width(50),GUILayout.Height(25)))
{
fontSizeOffset += 2;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space(10);
isFontSize = GUILayout.Toggle(isFontSize, "改变字体大小");
isFontBold = GUILayout.Toggle(isFontBold, "粗体");
EditorGUILayout.Space(10);
if(GUILayout.Button("Change Font",GUILayout.Width(100),GUILayout.Height(25)))
{
if (newFont == null)
{
Debug.LogError("New Font 不能为空!");
return;
}
FindPrefabs();
}
EditorGUILayout.EndVertical();
EditorGUI.EndChangeCheck();
}
public static void FindPrefabs()
{
string[] guids = AssetDatabase.FindAssets("t:Prefab", new[] {uiPrefabsDir});
foreach (string guid in guids)
{
string path = AssetDatabase.GUIDToAssetPath(guid);
GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(path);
DoChange(go);
}
AssetDatabase.SaveAssets();
}
public static void DoChange(GameObject target)
{
int cnt = 0;
UILabel[] labels = target.GetComponentsInChildren<UILabel>();
foreach (UILabel label in labels)
{
if (label.trueTypeFont )
{
//&& label.trueTypeFont.name != newFont.name
label.trueTypeFont = newFont;
if (isFontSize && 0 != fontSizeOffset)
{
label.fontSize += fontSizeOffset;
}
if (isFontBold)
{
label.fontStyle = FontStyle.Bold;
}
cnt++;
//Debug.LogFormat("ChangeFont_UILabelName:{0} ,FontName{1} ,FontSize{2}",label.name,label.trueTypeFont.name,label.fontSize);
}
}
EditorUtility.SetDirty(target);
Debug.LogFormat("Font Changed. Target:{0} ,Count:{1}",target.name,cnt);
}
}