Editor extension to group selected objects pressing Ctrl+G.
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