Last active
February 23, 2024 10:11
-
-
Save AShim3D/d76e2026c5655b3b34e2 to your computer and use it in GitHub Desktop.
Sort children by name in selected gameobjects. Unity3D 4.5+ (C#).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Works great. Thank you!
For prefabs, need to use this inside the prefab editor.
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
The script on the prefab
string curname;
//call this when instantiating to set the instances name from a databank
public void SetCurName(string newname)
{
curname = newname;
public string GetName()
{
return curname;
}