using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using System.IO; public class BatchRename : EditorWindow { private string folderPath = "please input the right path"; // 默认文件夹路径 private string oldKeyword = "oldkeyword"; // 旧关键词 private string newKeyword = "newkeyword"; // 新关键词 private bool renameNodes = false; // 是否修改 Prefab 节点的选项 [MenuItem("Window/Batch Rename")] // 在 Unity 菜单栏中创建工具项 public static void ShowWindow() { GetWindow("Batch Rename"); } private void OnGUI() { GUILayout.Label("Batch Rename Settings", EditorStyles.boldLabel); // 输入文件夹路径 folderPath = EditorGUILayout.TextField("Folder Path", folderPath); // 输入旧关键词 oldKeyword = EditorGUILayout.TextField("Old Keyword", oldKeyword); // 输入新关键词 newKeyword = EditorGUILayout.TextField("New Keyword", newKeyword); // 添加一个切换选项 renameNodes = EditorGUILayout.Toggle("Rename Prefab Nodes", renameNodes); // 按钮操作 if (GUILayout.Button("Rename")) { RenameAssets(); } } private void RenameAssets() { if (string.IsNullOrEmpty(folderPath) || string.IsNullOrEmpty(oldKeyword) || string.IsNullOrEmpty(newKeyword)) { Debug.LogError("Folder Path, Old Keyword, and New Keyword cannot be empty."); return; } string[] guids = AssetDatabase.FindAssets("t:Prefab", new string[] { folderPath }); // 搜索 Prefab 类型的资源 int renamedFiles = 0; int renamedNodes = 0; foreach (string guid in guids) { string path = AssetDatabase.GUIDToAssetPath(guid); string fileName = Path.GetFileNameWithoutExtension(path); // 获取文件名(无扩展名) string extension = Path.GetExtension(path); // 获取扩展名 // 检查文件名是否包含旧关键词 if (fileName.Contains(oldKeyword)) { string newName = fileName.Replace(oldKeyword, newKeyword); // 替换关键词 AssetDatabase.RenameAsset(path, newName); // 重命名文件 renamedFiles++; } // 加载 Prefab 并替换内部节点的名字(如果选中此功能) if (renameNodes) { GameObject prefab = AssetDatabase.LoadAssetAtPath(path); if (prefab != null) { renamedNodes += RenamePrefabNodes(prefab, oldKeyword, newKeyword); // 调用递归方法 PrefabUtility.SavePrefabAsset(prefab); // 保存 Prefab 更改 } } } AssetDatabase.SaveAssets(); // 保存修改 Debug.Log($"Batch rename completed! Renamed {renamedFiles} files and {(renameNodes ? renamedNodes.ToString() : "0")} nodes."); } private int RenamePrefabNodes(GameObject parent, string oldKeyword, string newKeyword) { int renameCount = 0; // 检查父对象本身 if (parent.name.Contains(oldKeyword)) { parent.name = parent.name.Replace(oldKeyword, newKeyword); // 替换节点名字 renameCount++; } // 遍历子对象 foreach (Transform child in parent.transform) { renameCount += RenamePrefabNodes(child.gameObject, oldKeyword, newKeyword); // 递归检查子对象 } return renameCount; } }