Skip to content

Instantly share code, notes, and snippets.

@AShim3D
Last active February 23, 2024 10:11
Show Gist options
  • Save AShim3D/d76e2026c5655b3b34e2 to your computer and use it in GitHub Desktop.
Save AShim3D/d76e2026c5655b3b34e2 to your computer and use it in GitHub Desktop.
Sort children by name in selected gameobjects. Unity3D 4.5+ (C#).
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public class TempTools {
[MenuItem ("AShim/SortChildrenByName")]
public static void SortChildrenByName() {
foreach (GameObject obj in Selection.gameObjects) {
List<Transform> children = new List<Transform>();
for (int i = obj.transform.childCount - 1; i >= 0; i--) {
Transform child = obj.transform.GetChild(i);
children.Add(child);
child.parent = null;
}
children.Sort((Transform t1, Transform t2) => { return t1.name.CompareTo(t2.name); });
foreach (Transform child in children) {
child.parent = obj.transform;
}
}
} // SortChildrenByName()
} // class TempTools
@gackt2
Copy link

gackt2 commented Mar 6, 2023

Works great. Thank you!
For prefabs, need to use this inside the prefab editor.

@ALI3NPANDA
Copy link

Method to sort all the children inside another children

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

public static class SortChildren
{
    [MenuItem("Setup/Sort All Children")]
    public static void SortAllChildren()
    {
        foreach (Transform t in Selection.transforms)
        {
            SortChildrenRecursively(t);
        }
    }

    public static void SortChildrenRecursively(Transform parent)
    {
        List<Transform> children = parent.Cast<Transform>().ToList();
        children.Sort((Transform t1, Transform t2) => { return t1.name.CompareTo(t2.name); });
        for (int i = 0; i < children.Count; ++i)
        {
            Undo.SetTransformParent(children[i], children[i].parent, "Sort Children");
            children[i].SetSiblingIndex(i);
        }
        
        foreach (Transform child in parent)
        {
            SortChildrenRecursively(child);
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment