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(){
Transform[] children = new Transform[transform.childCount];
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(){
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);
}
}
Explanation:
The interesting part is in these three lines:
int row = i / Columns;
int column = i % Columns;
transform.GetChild(i).position = new Vector2(column * Space, row * Space);
So what does it do?
First we calculate which row it should be in, by dividing the current index by the number of columns we want to use. Since these are two ints, the result is rounded down. So for the first four children we are performing the calculations: 0/4, 1/4, 2/4, and 3/4, all of which round down to row 0. The next four calculations are 4/4, 5/4, 6/4, and 7/4. These all round down to 1. If you add more children, they would go into row 2, 3, and so on.
Then we calculate the column, by calculating the remainder of those divisions, using the modulo operator (%). Those first four calculations, again, were 0/4, 1/4, 2/4, and 3/4. The remainder of each of those calculations are 0, 1, 2, and 3, respectively. The next four calculations have the same remainders (4/4, 5/4, 6/4, 7/4 go to 0, 1, 2, and 3)
We have now generated the row,column pairs necessary for layout: 0,0 0,1 0,2 0,3 1,0 1,1 1,2 and 1,3
Now that we know which row and column they belong in, we just need to get the world coordinates of those rows and columns. If I understood correctly, you wanted them each spaced apart by 2 units, so we multiply the current row and column by 2.0. 1,3 for example becomes 2.0,6.0