Last active
November 25, 2020 14:50
-
-
Save ginomessmer/e88596e367b5b0915aeeaf448a0be3aa to your computer and use it in GitHub Desktop.
Neat Unity3D editor script for grouping objects in hierarchy
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 System.Collections.Generic; | |
using System.Linq; | |
using UnityEditor; | |
using UnityEngine; | |
// Neat editor script for grouping objects in hierarchy by /u/SocialOfficer | |
// | |
public class HierarchyHelper | |
{ | |
public static string Suffix = "_Root"; | |
[MenuItem("GameObject/Organize/Merge in new or existing parent", false, -10)] | |
public static void Merge() | |
{ | |
var selection = Selection.objects.ToList(); | |
var first = Selection.activeGameObject; | |
string baseName = first.name; | |
string rootName = baseName + Suffix; | |
GameObject newRootParentObject; | |
var existingRoot = GameObject.Find(rootName); | |
if (existingRoot != null) | |
{ | |
newRootParentObject = existingRoot; | |
} | |
else | |
{ | |
newRootParentObject = new GameObject(); | |
newRootParentObject.name = baseName + Suffix; | |
newRootParentObject.transform.SetParent(first.transform.parent); | |
} | |
foreach(var item in selection) | |
{ | |
var gameObject = item as GameObject; | |
gameObject.name = baseName; | |
gameObject.transform.SetParent(newRootParentObject.transform); | |
} | |
} | |
[MenuItem("GameObject/Organize/Dissolve root container", false, -10)] | |
public static void DissolveParent() | |
{ | |
var selection = Selection.activeGameObject; | |
if (selection.name.EndsWith(Suffix)) | |
{ | |
List<GameObject> childObjects = new List<GameObject>(); | |
foreach(Transform child in selection.transform) | |
childObjects.Add(child.gameObject); | |
foreach(var gameObject in childObjects) | |
{ | |
gameObject.transform.SetParent(selection.transform.parent); | |
} | |
GameObject.DestroyImmediate(selection); | |
} | |
else | |
{ | |
Debug.LogError("Selected GameObject is not a valid root parent."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
lol