- Home /
"Center On Children" programmatically
Hi, Is there a way to use the "Center On Children" command (found under the GameObject menu) from a C# script?
I know I can figure out the centered position, and un-parent all children while I move the parent itself, and maybe "Center On Children" does exactly that, I dunno, but maybe it does something more efficient behind the scenes.
Thanks!
Answer by Bunny83 · Dec 13, 2013 at 03:52 AM
All this menu item does is this:
//C#
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class GO_Extensions
{
public static void CenterOnChildred(this Transform aParent)
{
var childs = aParent.Cast<Transform>().ToList();
var pos = Vector3.zero;
foreach(var C in childs)
{
pos += C.position;
C.parent = null;
}
pos /= childs.Count;
aParent.position = pos;
foreach(var C in childs)
C.parent = aParent;
}
}
With this class somewhere in your project you can simply use it like this on any transform:
transform.CenterOnChildred();
Of course it's possible to do it without unparenting the childs, but if you have to consider scaling and rotation of the parent which is quite nasty. This is the easiest way.
Thanks! I was wondering how to get a copy of the children, but this code throws me 2 errors (after creating a new C# script named 'GO_Extensions' and replaced the existing code with the one above):
Cannot convert type
UnityEngine.Transform' to >
System.Collections.Generic.IEnumerable' via a built-in conversionOperator
/=' cannot be applied to > operands of type
UnityEngine.Vector3' and `method group'
I assume I could do a foreach loop of Transforms on the parent's transform, but since it's not a copy, it would probably get changed during the iteration.. and I have no idea on the second error :) Thanks
Yes, sorry ;) I didn't test this yesterday. I always forget that you can't directly cast the IEnumerable to the generic IEnumerable. All you have to change is this:
var childs = aParent.Cast<Transform>().ToList();
I'll edit my answer