Last active
June 25, 2020 08:43
-
-
Save jfranmora/b7d478e979aa69f26d424b4925a91720 to your computer and use it in GitHub Desktop.
Editor extension to group selected objects pressing Ctrl+G.
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; | |
using UnityEditor; | |
using UnityEngine; | |
public static class GroupGameObjects | |
{ | |
[MenuItem("Edit/Group Items %g")] | |
public static void GroupSelected() | |
{ | |
if (Selection.gameObjects.Length > 1) | |
{ | |
// Calculate selection center | |
Vector3 center = Vector3.zero; | |
foreach (var go in Selection.gameObjects) | |
{ | |
center += go.transform.position; | |
} | |
center /= Selection.gameObjects.Length; | |
// Spawn new GameObject | |
GameObject group = new GameObject("Item Group"); | |
group.transform.position = center; | |
using (new UndoGroup($"Group {Selection.gameObjects.Length} objects")) | |
{ | |
Undo.RegisterCreatedObjectUndo(group, ""); | |
foreach (var go in Selection.gameObjects) | |
{ | |
// Set parent | |
Undo.SetTransformParent(go.transform, group.transform, ""); | |
} | |
EditorGUIUtility.PingObject(group); | |
Selection.activeGameObject = group; | |
} | |
} | |
} | |
} | |
public class UndoGroup : IDisposable | |
{ | |
private readonly int group; | |
public UndoGroup(string groupName) | |
{ | |
Undo.SetCurrentGroupName(groupName); | |
group = Undo.GetCurrentGroup(); | |
} | |
public void Dispose() | |
{ | |
Undo.CollapseUndoOperations(group); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment