using UnityEditor;
using UnityEngine;
using System.Linq;
public class RenameTool : EditorWindow
{
private string newName = "";
private static GameObject[] selectedObjects;
[MenuItem("Tools/Rename Selected Asset")]
private static void Init()
{
var window = GetWindow(typeof(RenameTool));
window.titleContent = new GUIContent("Rename Tool");
window.Show();
selectedObjects = Selection.gameObjects;
if (selectedObjects.Length == 0)
{
Debug.LogWarning("没有选中任何物体!");
return;
}
// 排序选中的物体
selectedObjects = selectedObjects.OrderBy(o => GetHierarchyPath(o.transform)).ToArray();
}
void OnGUI()
{
newName = EditorGUILayout.TextField("New Name:", newName);
if (GUILayout.Button("Rename"))
{
RenameSelectedAsset();
}
}
void RenameSelectedAsset()
{
for (int i = 0; i < selectedObjects.Length; i++)
{
selectedObjects[i].name = $"{newName}_{(i + 1).ToString().PadLeft(3, '0')}";//不足三位前面补0
}
}
// 获取物体在层次结构中的路径
private static string GetHierarchyPath(Transform transform)
{
string path = "";
while (transform != null)
{
path = transform.GetSiblingIndex().ToString("D4") + path;
transform = transform.parent;
}
return path;
}
}