SceneFontReplacer.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEditor;
  4. using UnityEditor.SceneManagement;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. public class GlobalSceneFontReplacer
  8. {
  9. [MenuItem("Tools/全项目场景 + Prefab 替换字体")]
  10. static void ReplaceFontInAllScenesAndPrefabs()
  11. {
  12. string fontPath = "Assets/BowArrow/Fonts/HarmonyOS_Sans_SC_Regular.ttf";
  13. Font newFont = AssetDatabase.LoadAssetAtPath<Font>(fontPath);
  14. if (newFont == null)
  15. {
  16. Debug.LogError("找不到目标字体!");
  17. return;
  18. }
  19. int totalChanges = 0;
  20. // ✅ 替换所有 prefab
  21. string[] prefabGuids = AssetDatabase.FindAssets("t:Prefab");
  22. foreach (string guid in prefabGuids)
  23. {
  24. string assetPath = AssetDatabase.GUIDToAssetPath(guid);
  25. GameObject obj = AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
  26. if (obj == null) continue;
  27. Text[] texts = obj.GetComponentsInChildren<Text>(true);
  28. bool changed = false;
  29. foreach (Text text in texts)
  30. {
  31. if (text.font != null && text.font.name == "Arial")
  32. {
  33. Undo.RecordObject(text, "Replace Font");
  34. text.font = newFont;
  35. EditorUtility.SetDirty(text);
  36. changed = true;
  37. totalChanges++;
  38. }
  39. }
  40. if (changed)
  41. {
  42. PrefabUtility.SavePrefabAsset(obj);
  43. AssetDatabase.SaveAssets();
  44. }
  45. }
  46. // ✅ 替换所有场景
  47. string[] sceneGuids = AssetDatabase.FindAssets("t:Scene");
  48. foreach (string guid in sceneGuids)
  49. {
  50. string scenePath = AssetDatabase.GUIDToAssetPath(guid);
  51. var scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
  52. bool changed = false;
  53. foreach (GameObject root in scene.GetRootGameObjects())
  54. {
  55. Text[] texts = root.GetComponentsInChildren<Text>(true);
  56. foreach (Text text in texts)
  57. {
  58. if (text.font != null && text.font.name == "Arial")
  59. {
  60. Undo.RecordObject(text, "Replace Font");
  61. text.font = newFont;
  62. EditorUtility.SetDirty(text);
  63. changed = true;
  64. totalChanges++;
  65. }
  66. }
  67. }
  68. if (changed)
  69. {
  70. EditorSceneManager.MarkSceneDirty(scene);
  71. EditorSceneManager.SaveScene(scene);
  72. }
  73. }
  74. Debug.Log($"✅ 场景 + Prefab 字体替换完成,共替换 {totalChanges} 个 Text 字体。");
  75. }
  76. }