csharp
#if UNITY_EDITOR
using UnityEngine;
using UnityEngine.UI; // 引用UI命名空间以使用Text组件
using UnityEditor;
using UnityEditor.SceneManagement;
using System.Collections.Generic;
using System.Linq;
public class CheckLegacyFontsTool : EditorWindow
{
private Vector2 scrollPosition;
private List<GameObject> legacyFontObjects = new List<GameObject>();
// 添加菜单项
[MenuItem("Tools/检查场景中的LegacyRuntime字体")]
public static void ShowWindow()
{
GetWindow<CheckLegacyFontsTool>("字体检查工具");
}
void OnGUI()
{
GUILayout.Label("场景字体检查工具", EditorStyles.boldLabel);
GUILayout.Space(10);
if (GUILayout.Button("扫描当前场景"))
{
ScanCurrentScene();
}
GUILayout.Space(10);
GUILayout.Label($"发现 {legacyFontObjects.Count} 个使用LegacyRuntime字体的对象:");
// 滚动视图显示结果列表
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
foreach (var obj in legacyFontObjects)
{
EditorGUILayout.BeginHorizontal();
GUILayout.Label(obj.name, GUILayout.Width(200));
if (GUILayout.Button("选择", GUILayout.Width(60)))
{
Selection.activeGameObject = obj;
EditorGUIUtility.PingObject(obj);
}
EditorGUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
}
private void ScanCurrentScene()
{
legacyFontObjects.Clear();
// 获取当前场景中所有的GameObject(更高效的查询可参考LINQ to GameObject思想[citation:4])
Text[] allTexts = Resources.FindObjectsOfTypeAll<Text>();
foreach (Text text in allTexts)
{
// 重要:确保只处理场景中的对象,排除预制体等资源
if (!EditorUtility.IsPersistent(text.transform.root.gameObject) && text.gameObject.scene.IsValid())
{
// 检查字体名称是否为"LegacyRuntime"[citation:5]
if (text.font != null && text.font.name.Contains("LegacyRuntime"))
{
legacyFontObjects.Add(text.gameObject);
Debug.LogWarning($"发现LegacyRuntime字体: {GetGameObjectPath(text.gameObject)}", text.gameObject);
}
}
}
if (legacyFontObjects.Count == 0)
{
Debug.Log("扫描完成:当前场景中未发现使用LegacyRuntime字体的Text组件。");
}
else
{
Debug.Log($"扫描完成:共发现 {legacyFontObjects.Count} 个Text组件使用了LegacyRuntime字体。详细信息已输出至控制台。");
}
// 刷新编辑器窗口显示
Repaint();
}
// 辅助方法:获取GameObject在场景中的完整路径
private string GetGameObjectPath(GameObject obj)
{
if (obj == null) return "";
string path = obj.name;
while (obj.transform.parent != null)
{
obj = obj.transform.parent.gameObject;
path = obj.name + "/" + path;
}
return path;
}
}
#endif