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.
//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.