Skip to content

Instantly share code, notes, and snippets.

@jfranmora
Last active June 25, 2020 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfranmora/b7d478e979aa69f26d424b4925a91720 to your computer and use it in GitHub Desktop.
Save jfranmora/b7d478e979aa69f26d424b4925a91720 to your computer and use it in GitHub Desktop.
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