Skip to main content
1 of 3
Ed Marty
  • 5.2k
  • 1
  • 13
  • 15
private const int Columns = 4;
private const float Space = 2.0f;
private void ArrangeChildren(Transform[] children) {
    for (int i = 0; i < children.Length; ++i) {
        int row = i / Columns;
        int column = i % Columns;
        children[i].position = new Vector2(column * Space, row * Space);
    }
}

Whenever you want to perform the layout, collect the children into an array, as you have done in your example, then call this method, passing in that array. Note however that I would recommend not necessarily calling this in Update, if nothing else is changing the children. I assume the children are changed while running the game (otherwise you wouldn’t need to have code to arrange them) so you only need to run this when a child is added or removed. You can do this inside of the method OnTransformChildrenChanged:

private void OnTransformChildrenChanged(){
    for (int i=0; i<transform.childCount; i++) {
        children[i]=transform.GetChild(i);
    }
    ArrangeChildren(children);
}

Finally, I left your method of collecting children into an array in place, assuming you needed that array for something else as well. If that’s not the case, then there’s no need to allocate extra memory or loop through the children twice:

private const int Columns = 4;
private const float Space = 2.0f;
private void OnTransformChildrenChanged(){
    Transform[] children = new Transform[transform.childCount];
    for (int i=0; i<transform.childCount; i++) {
        int row = i / Columns;
        int column = i % Columns;
        transform.GetChild(i).position = new Vector2(column * Space, row * Space);
    }
}
Ed Marty
  • 5.2k
  • 1
  • 13
  • 15