Unity Editor批量重命名GameObject和Prefab

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class RenameEidtor : Editor
{
    static readonly char SpaceChar = '_';

    [MenuItem("GameObject/Tools/ReNameSort", false , 11)]
    public static void FnmRenameObjs()
    {
        GameObject[] objs = Selection.gameObjects;

        if (objs.Length < 2) return;

        GameObject firstObj = FnmGetMinNum(objs, out int currentNum);

        if (!IsFormatCorrect(firstObj)) firstObj.name += "_0";

        string baseName = firstObj.name.Substring(0, firstObj.name.LastIndexOf(SpaceChar) + 1);

        Transform parent = firstObj.transform.parent;

        int count = FnmClassify(parent, objs);

        int num = FnmGetNum(firstObj);

        //Debug.Log(firstObj.name + ", " + count + ", " + currentNum + ", " + num);
        for (int i = 1; i < count; i++)
        {
            parent.GetChild(i + currentNum).name = baseName + (num + i);
        }
    }

    static int FnmClassify(Transform templateP, GameObject[] objs)
    {
        int count = 0;

        for (int i = 0; i < objs.Length; i++)
        {
            if(objs[i].transform.parent == templateP)
            {
                count++;
            }
        }

        return count;
    }

    static GameObject FnmGetMinNum(GameObject[] objs, out int min)
    {
        min = objs[0].transform.GetSiblingIndex();
        GameObject minObj = objs[0];
        int num;

        for (int i = 1; i < objs.Length; i++)
        {
            num = objs[i].transform.GetSiblingIndex();
            if (num < min)
            {
                min = objs[i].transform.GetSiblingIndex();
                minObj = objs[i];
            }
        }

        return minObj;
    }

    static int FnmGetNum(GameObject obj)
    {
        if (!obj.name.Contains(SpaceChar.ToString())) return 10000;
        string baseName = obj.name.Substring(0, obj.name.LastIndexOf(SpaceChar) + 1);
        return int.Parse(obj.name.Replace(baseName, ""));
    }

    static bool IsFormatCorrect(GameObject obj)
    {
        string objName = obj.name;

        if (!objName.Contains(SpaceChar.ToString())) return false;

        string baseName = objName.Substring(0, objName.LastIndexOf(SpaceChar) + 1);

        return int.TryParse(objName.Replace(baseName, ""), out _);
    }
}

 

posted @ 2022-12-20 18:30  田丰  阅读(444)  评论(0编辑  收藏  举报