Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEditor;
- public class CenteredParentMenu
- {
- [MenuItem("GameObject/Create Centered Empty Parent", false, 0)]
- static void CreateCenteredEmptyParent(MenuCommand menuCommand)
- {
- // Run the operation only if it's triggered on the first selected object
- if (menuCommand.context != Selection.activeTransform.gameObject)
- {
- return;
- }
- // Get the selected objects in the hierarchy
- GameObject[] selectedObjects = Selection.gameObjects;
- if (selectedObjects.Length == 0)
- {
- Debug.LogWarning("No objects selected. Please select at least one object in the hierarchy.");
- return;
- }
- // Get the parent of the first selected object (assuming all selected objects share the same parent)
- Transform originalParent = selectedObjects[0].transform.parent;
- // Validate that all selected objects share the same parent
- foreach (GameObject go in selectedObjects)
- {
- if (go.transform.parent != originalParent)
- {
- Debug.LogWarning("Cannot select children from different family trees.");
- return;
- }
- }
- // Create the new parent GameObject and register it in the Undo system
- GameObject parentObject = new GameObject("CenteredParent");
- Undo.RegisterCreatedObjectUndo(parentObject, "Create Centered Empty Parent");
- // Calculate the center of all selected objects
- Vector3 center = Vector3.zero;
- foreach (GameObject obj in selectedObjects)
- {
- center += obj.transform.position;
- }
- center /= selectedObjects.Length;
- // Set the new parent object's position to the calculated center
- parentObject.transform.position = center;
- // Set the new parent object under the original parent
- if (originalParent != null)
- {
- Undo.SetTransformParent(parentObject.transform, originalParent, "Reparent Centered Empty");
- }
- // Move all selected objects under the new parent and preserve their world positions
- foreach (GameObject obj in selectedObjects)
- {
- Undo.SetTransformParent(obj.transform, parentObject.transform, "Parent Selected Objects");
- }
- // Ensure that after undo, the objects retain their original positions
- foreach (GameObject obj in selectedObjects)
- {
- Undo.RecordObject(obj.transform, "Move Object");
- }
- // Select the new parent object in the hierarchy
- Selection.activeGameObject = parentObject;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement