- Home /
Question by
alexanderameye · Jul 16, 2017 at 09:50 AM ·
boundsparent-childcenterparent transformpivot-point
How to get the center of an empty parent gameobject?
Hey, I have this scene:
With the transform handle set to 'center'. 'GameObject' is just an empty gameobject. How can I get the position of that center tool handle?
Comment
Answer by Bunny83 · Jul 16, 2017 at 10:12 AM
You can't. At least Unity doesn't calculate that for you. In the editor it's a feature that is built-into the editor.
The best approach would be to iterate over all Renderer in all child objects, gather the worldspace bounds values and combine them with Bounds.Encapsulate.
Vector3 GetCenter()
{
var rends = GetComponentsInChildren<Renderer>();
if (rends.Length == 0)
return transform.position;
var b = rends[0].bounds;
for(int i = 1; i < rends.Length; i++)
{
b = b.Encapsulate(rends[i].bounds);
}
return b.center;
}
Encapsulate returns void so I removed the 'b = '. Then it kind of worked but when I put a gameobject at the position the function returns, it's still not exactly at the position it should be but slightly off.