53 lines
1.4 KiB
C#
53 lines
1.4 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEditor;
|
|
using System.Linq;
|
|
|
|
public class ChildSort : Editor
|
|
{
|
|
[MenuItem("Tools/Sort Children By Name")]
|
|
private static void SortChildrenByNameMenu()
|
|
{
|
|
// 获取当前选中的物体
|
|
GameObject selected = Selection.activeGameObject;
|
|
|
|
if (selected == null)
|
|
{
|
|
Debug.LogError("请先选择一个父物体!");
|
|
return;
|
|
}
|
|
|
|
// 获取所有子物体
|
|
List<Transform> children = new List<Transform>();
|
|
foreach (Transform child in selected.transform)
|
|
{
|
|
children.Add(child);
|
|
}
|
|
|
|
// 排序逻辑(按名字中的数字)
|
|
children = children.OrderBy(child =>
|
|
{
|
|
string name = child.name;
|
|
int number = ExtractNumber(name);
|
|
return number;
|
|
}).ToList();
|
|
|
|
// 按排序结果重新设置子物体的层级
|
|
for (int i = 0; i < children.Count; i++)
|
|
{
|
|
children[i].SetSiblingIndex(i);
|
|
}
|
|
|
|
Debug.Log($"已对 {selected.name} 下的子物体按名字排序!");
|
|
}
|
|
|
|
static int ExtractNumber(string name)
|
|
{
|
|
int number = 0;
|
|
string digits = new string(name.Where(char.IsDigit).ToArray());
|
|
int.TryParse(digits, out number);
|
|
return number;
|
|
}
|
|
}
|