Created
October 17, 2019 09:59
-
-
Save codewings/e0e08d112fec1ce8091db0184069acd5 to your computer and use it in GitHub Desktop.
Create a pivot from selected GameObjects in unity
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 UnityEngine; | |
using UnityEditor; | |
using System.Linq; | |
public class CreatePivotFromSelection | |
{ | |
static void CreatePivot(Vector3 offset) | |
{ | |
if (Selection.gameObjects == null || Selection.gameObjects.Length <= 0) | |
return; | |
var pivot = new GameObject(); | |
var bounds = new Bounds(); | |
foreach (var g in Selection.gameObjects) | |
{ | |
var m = g.GetComponent<MeshFilter>(); | |
if (m) | |
{ | |
var xform = g.transform; | |
var bbox = new Bounds(xform.TransformPoint(m.sharedMesh.bounds.center), xform.TransformVector(m.sharedMesh.bounds.size)); | |
if (g == Selection.gameObjects[0]) | |
{ | |
bounds = bbox; | |
} | |
else | |
{ | |
bounds.Encapsulate(bbox); | |
} | |
} | |
} | |
pivot.transform.position = bounds.center + new Vector3(bounds.size.x * offset.x, bounds.size.y * offset.y, bounds.size.z * offset.z); | |
var movable = new List<GameObject>(Selection.gameObjects); | |
foreach (var g in Selection.gameObjects) | |
{ | |
if (g.transform.parent == null || g.transform.parent.parent == null) | |
{ | |
var old = g.transform.parent; | |
g.transform.parent = pivot.transform; | |
movable.Remove(g); | |
for (var i = 0; i < g.transform.childCount; ++i) | |
{ | |
var child = g.transform.GetChild(i); | |
if (Selection.gameObjects.Contains(child.gameObject)) | |
{ | |
movable.Remove(child.gameObject); | |
} | |
else | |
{ | |
child.parent = old; | |
} | |
} | |
} | |
} | |
foreach (var g in movable) | |
{ | |
g.transform.parent = pivot.transform; | |
} | |
} | |
[MenuItem("GameObject/Create Ground Pivot from Selection", false, 11)] | |
public static void CreateGroundPivot() | |
{ | |
CreatePivot(new Vector3(0, -0.5f, 0)); | |
} | |
[MenuItem("GameObject/Create Center Pivot from Selection", false, 12)] | |
public static void CreateCenterPivot() | |
{ | |
CreatePivot(new Vector3(0, 0, 0)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
amazing. love it. it works!