using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine.UI;
using System.Linq;
using UnityEngine.SceneManagement;
using System.Text;
using UnityEditor.SceneManagement;
/// <summary>
/// 查找替换工程场景中Text的Font
/// </summary>
public class ChangePrefabFont : EditorWindow
{
[MenuItem("Tools/替换字体/Text")]
static void GetWindow()
{
ChangePrefabFont window = EditorWindow.GetWindow<ChangePrefabFont>("Text字体替换窗口");
window.minSize = new Vector2(600, 500);
window.Show();
}
#region 属性
private List<string> fontsOnAssets = new List<string>();
private List<bool> textPaidFontRelpace = new List<bool>();
private List<Font> textReplaceFonts = new List<Font>();
private List<GameObject> prefabs = new List<GameObject>();
private Dictionary<string, List<GameObject>> Dic_Font_Prefabs = new Dictionary<string, List<GameObject>>();
private ReorderableList reorderableList;
private Vector2 scrollPos;
private Vector2 fontOptionsScrollPos;
private bool needsRefresh = false;
private bool showPrefabList = true;
#endregion
#region Unity生命周期
private void OnEnable()
{
InitFont();
RefreshPrefabs();
}
private void OnGUI()
{
if (needsRefresh)
{
RefreshPrefabs();
needsRefresh = false;
}
DrawHeader();
DrawFontReplacementOptions();
DrawReplaceButton();
DrawPrefabList();
}
#endregion
#region UI绘制方法
private void DrawHeader()
{
EditorGUILayout.Space();
EditorGUILayout.LabelField("字体替换工具", EditorStyles.boldLabel);
EditorGUILayout.HelpBox("此工具用于查找和替换工程中所有预制体和场景对象中的Text组件字体", MessageType.Info);
EditorGUILayout.Space();
}
private void DrawFontReplacementOptions()
{
EditorGUILayout.LabelField("字体替换选项", EditorStyles.boldLabel);
// 添加字体选项的滚动区域
fontOptionsScrollPos = EditorGUILayout.BeginScrollView(fontOptionsScrollPos, GUILayout.Height(300));
for (int i = 0; i < fontsOnAssets.Count; i++)
{
DrawFontOption(i);
}
EditorGUILayout.EndScrollView();
// 显示字体总数信息
EditorGUILayout.LabelField($"总共发现 {fontsOnAssets.Count} 种字体", EditorStyles.miniLabel);
}
private void DrawFontOption(int index)
{
EditorGUILayout.BeginVertical("box");
// 第一行:字体名称和替换开关
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField($"字体: {fontsOnAssets[index]}", EditorStyles.boldLabel, GUILayout.Width(150));
bool oldValue = textPaidFontRelpace[index];
textPaidFontRelpace[index] = EditorGUILayout.Toggle("替换此字体", textPaidFontRelpace[index]);
if (oldValue != textPaidFontRelpace[index])
{
needsRefresh = true;
}
EditorGUILayout.EndHorizontal();
// 第二行:预制体数量和替换字体选择
if (textPaidFontRelpace[index])
{
EditorGUILayout.BeginHorizontal();
int prefabCount = GetGetUseFontPrefabCount(fontsOnAssets[index]);
EditorGUILayout.LabelField($"影响预制体: {prefabCount}个", GUILayout.Width(120));
EditorGUILayout.LabelField("替换为:", GUILayout.Width(40));
textReplaceFonts[index] = (Font)EditorGUILayout.ObjectField(textReplaceFonts[index], typeof(Font), false);
EditorGUILayout.EndHorizontal();
}
else
{
EditorGUILayout.LabelField($"使用此字体的预制体: {GetGetUseFontPrefabCount(fontsOnAssets[index])}个");
}
EditorGUILayout.EndVertical();
EditorGUILayout.Space();
}
private void DrawReplaceButton()
{
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("刷新数据", GUILayout.Height(25)))
{
InitFont();
RefreshPrefabs();
}
GUI.enabled = prefabs.Count > 0;
if (GUILayout.Button("开始替换字体", GUILayout.Height(30)))
{
StartFontReplacement();
}
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
}
private void DrawPrefabList()
{
showPrefabList = EditorGUILayout.Foldout(showPrefabList, $"将受影响的预制体列表 ({prefabs.Count}个)", true);
if (!showPrefabList) return;
if (prefabs.Count == 0)
{
EditorGUILayout.HelpBox("没有需要替换字体的预制体。请在上方选择要替换的字体。", MessageType.Info);
return;
}
if (reorderableList == null)
{
InitReorderableList();
}
EditorGUILayout.BeginVertical("box");
scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Height(300));
reorderableList.DoLayoutList();
EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical();
}
#endregion
#region 核心逻辑方法
private void StartFontReplacement()
{
var validationResult = ValidateReplacement();
if (!validationResult.isValid)
{
EditorUtility.DisplayDialog("提示", validationResult.errorMessage, "确定");
return;
}
if (EditorUtility.DisplayDialog("确认替换", validationResult.confirmationMessage, "确定", "取消"))
{
ExecuteFontReplacement(validationResult.replacements);
SaveChanges();
EditorUtility.DisplayDialog("提示", "字体替换完成!", "确定");
}
}
private (bool isValid, string errorMessage, string confirmationMessage, Dictionary<string, Font> replacements) ValidateReplacement()
{
var replacements = new Dictionary<string, Font>();
StringBuilder confirmationMessage = new StringBuilder("将进行以下字体替换:\n\n");
for (int i = 0; i < textPaidFontRelpace.Count; i++)
{
if (!textPaidFontRelpace[i]) continue;
if (textReplaceFonts[i] == null)
return (false, $"【{fontsOnAssets[i]}】的替代字体为空!", null, null);
if (!Dic_Font_Prefabs.ContainsKey(fontsOnAssets[i]) || Dic_Font_Prefabs[fontsOnAssets[i]].Count == 0)
return (false, $"使用了【{fontsOnAssets[i]}】字体的预制体数量为0!", null, null);
replacements.Add(fontsOnAssets[i], textReplaceFonts[i]);
confirmationMessage.AppendLine($"• {fontsOnAssets[i]} → {textReplaceFonts[i].name}");
}
if (replacements.Count == 0)
return (false, "请至少选择一个要替换的字体!", null, null);
confirmationMessage.Append($"\n总共会影响 {prefabs.Count} 个预制体/场景对象。");
return (true, null, confirmationMessage.ToString(), replacements);
}
private void ExecuteFontReplacement(Dictionary<string, Font> replacements)
{
int totalReplaced = 0;
foreach (var replacement in replacements)
{
int replacedInFont = ReplaceFont(Dic_Font_Prefabs[replacement.Key], replacement.Key, replacement.Value);
totalReplaced += replacedInFont;
Debug.Log($"字体 {replacement.Key} 替换为 {replacement.Value.name},影响了 {replacedInFont} 个Text组件");
}
Debug.Log($"字体替换完成!总共替换了 {totalReplaced} 个Text组件");
}
private void SaveChanges()
{
bool hasSceneObjects = false;
bool hasPrefabAssets = false;
foreach (var gameObject in prefabs)
{
if (PrefabUtility.IsPartOfPrefabAsset(gameObject))
{
// 预制体资源
EditorUtility.SetDirty(gameObject);
hasPrefabAssets = true;
}
else
{
// 场景中的对象
EditorUtility.SetDirty(gameObject);
hasSceneObjects = true;
// 标记场景为脏
var scene = gameObject.scene;
if (scene.IsValid())
{
EditorSceneManager.MarkSceneDirty(scene);
}
}
}
if (hasPrefabAssets)
{
AssetDatabase.SaveAssets();
}
if (hasSceneObjects)
{
EditorSceneManager.SaveOpenScenes();
}
AssetDatabase.Refresh();
}
#endregion
#region 初始化方法
/// <summary>
/// 字体相关初始化
/// </summary>
private void InitFont()
{
textPaidFontRelpace.Clear();
textReplaceFonts.Clear();
fontsOnAssets = FindAllFonts();
foreach (var item in fontsOnAssets)
{
textPaidFontRelpace.Add(false);
textReplaceFonts.Add(null);
}
}
/// <summary>
/// 刷新预制体数据
/// </summary>
private void RefreshPrefabs()
{
var allPrefabs = GetAllPrefabByAssetDatabase();
FilterNoTextPrefabs(allPrefabs);
// 根据选择状态重新构建prefabs列表
prefabs.Clear();
foreach (var item in Dic_Font_Prefabs)
{
if (ShouldIncludeFont(item.Key))
{
prefabs.AddRange(item.Value);
}
}
prefabs = prefabs.Distinct().ToList();
// 刷新ReorderableList
if (reorderableList != null)
{
reorderableList.list = prefabs;
}
}
private bool ShouldIncludeFont(string fontName)
{
int index = fontsOnAssets.IndexOf(fontName);
return index >= 0 && textPaidFontRelpace[index];
}
private void InitReorderableList()
{
reorderableList = new ReorderableList(prefabs, typeof(GameObject), true, true, true, true);
reorderableList.drawHeaderCallback = DrawHeader;
reorderableList.drawElementCallback = DrawElement;
reorderableList.onAddCallback = AddItem;
reorderableList.onRemoveCallback = RemoveItem;
}
#endregion
#region ReorderableList回调
private void DrawHeader(Rect rect)
{
EditorGUI.LabelField(rect, "将受影响的预制体列表 (" + prefabs.Count + "个)");
}
private void DrawElement(Rect rect, int index, bool isActive, bool isFocused)
{
if (index >= prefabs.Count) return;
rect.height -= 4;
rect.y += 2;
EditorGUI.BeginDisabledGroup(true);
prefabs[index] = (GameObject)EditorGUI.ObjectField(rect, "对象", prefabs[index], typeof(GameObject), true);
EditorGUI.EndDisabledGroup();
}
private void AddItem(ReorderableList list)
{
// 禁用手动添加,因为列表是自动生成的
EditorUtility.DisplayDialog("提示", "此列表是自动生成的,无法手动添加项目。", "确定");
}
private void RemoveItem(ReorderableList list)
{
// 禁用手动删除,因为列表是自动生成的
EditorUtility.DisplayDialog("提示", "此列表是自动生成的,无法手动删除项目。", "确定");
}
#endregion
#region 功能方法
#region 查找和过滤
/// <summary>
/// 找到工程和场景中的含有Text组件的对象
/// </summary>
private List<GameObject> GetAllPrefabByAssetDatabase(params string[] path)
{
List<GameObject> _prefabList = new List<GameObject>();
// 获取所有预制体
string[] _guids = AssetDatabase.FindAssets("t:Prefab", path);
foreach (var _guid in _guids)
{
string _prefabPath = AssetDatabase.GUIDToAssetPath(_guid);
GameObject _prefab = AssetDatabase.LoadAssetAtPath(_prefabPath, typeof(GameObject)) as GameObject;
if (_prefab != null)
{
_prefabList.Add(_prefab);
}
}
// 获取场景中的Text对象
#if UNITY_2020_1_OR_NEWER
Text[] texts = GameObject.FindObjectsOfType<Text>(true);
foreach (var text in texts)
{
if (!_prefabList.Contains(text.gameObject))
{
_prefabList.Add(text.gameObject);
}
}
#else
Scene activeScene = EditorSceneManager.GetActiveScene();
GameObject[] allObjectsInScene = activeScene.GetRootGameObjects();
foreach (var obj in allObjectsInScene)
{
Text[] texts = obj.GetComponentsInChildren<Text>(true);
foreach (var text in texts)
{
if (!_prefabList.Contains(text.gameObject))
{
_prefabList.Add(text.gameObject);
}
}
}
#endif
return _prefabList;
}
/// <summary>
/// 过滤没有包含Text的预制体,并按字体分类
/// </summary>
private void FilterNoTextPrefabs(List<GameObject> allPrefabs)
{
Dic_Font_Prefabs.Clear();
foreach (var prefab in allPrefabs)
{
Text[] texts = prefab.GetComponentsInChildren<Text>(true);
if (texts.Length == 0) continue;
foreach (var text in texts)
{
if (text.font != null)
{
string fontName = text.font.name;
if (!Dic_Font_Prefabs.ContainsKey(fontName))
{
Dic_Font_Prefabs.Add(fontName, new List<GameObject>());
}
if (!Dic_Font_Prefabs[fontName].Contains(prefab))
{
Dic_Font_Prefabs[fontName].Add(prefab);
}
}
}
}
}
/// <summary>
/// 找到工程中的所有字体文件
/// </summary>
private List<string> FindAllFonts()
{
HashSet<string> fontSet = new HashSet<string>();
// 获取所有字体文件
string[] fontGUIDs = AssetDatabase.FindAssets("t:Font");
foreach (string fontGUID in fontGUIDs)
{
string fontPath = AssetDatabase.GUIDToAssetPath(fontGUID);
Font font = AssetDatabase.LoadAssetAtPath<Font>(fontPath);
if (font != null)
{
fontSet.Add(font.name);
}
}

// 添加默认字体
fontSet.Add("Arial");
// 添加所有在预制体中使用的字体(即使不在Assets中)
foreach (var fontName in Dic_Font_Prefabs.Keys)
{
fontSet.Add(fontName);
}
return fontSet.OrderBy(name => name).ToList();
}
#endregion
#region 替换字体方法
/// <summary>
/// 替换Text的字体
/// </summary>
/// <returns>替换的Text组件数量</returns>
private int ReplaceFont(List<GameObject> gameObjects, string fontName, Font font)
{
int replacedCount = 0;
foreach (var go in gameObjects)
{
Text[] texts = go.GetComponentsInChildren<Text>(true);
foreach (var text in texts)
{
if (text.font != null && text.font.name == fontName)
{
text.font = font;
replacedCount++;
// 标记对象为脏
if (PrefabUtility.IsPartOfPrefabAsset(go))
{
EditorUtility.SetDirty(go);
}
else
{
EditorUtility.SetDirty(text);
}
}
}
}
return replacedCount;
}
#endregion
private List<GameObject> GetUseFontPrefabs(string font)
{
return Dic_Font_Prefabs.ContainsKey(font) ? Dic_Font_Prefabs[font] : null;
}
private int GetGetUseFontPrefabCount(string font)
{
List<GameObject> temp = GetUseFontPrefabs(font);
return temp == null ? 0 : temp.Count;
}
#endregion
}
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删