I have a UI panel that has GridLayoutGroup component. I will add to this panel child UI panels by code. Sometimes there will be 5 children, sometimes 9 and there will be more. When I add these children inside GridLayoutGroup, there will be some empty spaces or children will be outside of my panel.
How to make added children scaled so they fill all space inside GridLayoutGroup ?
I guess you could replace the GridLayoutGroup with 9 HorizontalLayoutGroups nested inside a VerticalLayoutGroup, and set all of them to have child force expand on. That'll make the empty ones take up zero space, and the rest of them take up the remainder. I'm pretty sure that the GridLayoutGroup is designed specifically to not resize it's cells based on the number that are filled.
I found a solution to this but it involves creating a new GridLayoutGroup class so it is a bit hacky.
It lets the grid position the elements normally, then uses the width of the grid to calculate the size the cells need to be to span the entire row.
[57985-stretchygrid.png*_|57985]
First grab the source of the original grid layout from Unity’s bitbucket [here][1] . Create a new script, pasting that code in and changing the name (to something like StretchyGridLayoutGroup.
With this code: float realsize = ((width - (spacing[0] * (actualCellCountX - 1))) / actualCellCountX); SetChildAlongAxis(rectChildren_, 0, startOffset.x + (realsize + spacing[0]) * positionX, realsize);_ And now the children will regrow to fill the entire area of the grid. They regrow based on how the grid positioned the cells, so if the grid decided 1 cell per row, it would take up the whole row, but if the grid decides 2 per row then the 2 cells grow to fill. So first the regular layout code does it’s thing, then we grow our cells based on our width. If this isn’t exactly what you are looking for, hopefully it at least helps!
_[1]: https://bitbucket.org/Unity-Technologies/ui/src/4f3cf8d16c1d8c6e681541a292855792e50b392e/UnityEngine.UI/UI/Core/Layout/GridLayoutGroup.cs?at=5.2&fileviewer=file-view-default*_
_
For us, we had to check and make sure all the children of the grid, had their scale to one, because the scale gets changed for some reason.
Hopefully helps somebody!
This has been an issue so many times for me that I set the localscale = Vector3.one; as standard practice every time I dynamically add to a grid.
I guess you could replace the GridLayoutGroup with 9 HorizontalLayoutGroups nested inside a VerticalLayoutGroup, and set all of them to have child force expand on. That'll make the empty ones take up zero space, and the rest of them take up the remainder. I'm pretty sure that the GridLayoutGroup is designed specifically to not resize it's cells based on the number that are filled.
– BasteOK. I made as you suggested. Worked well.
– SuperMasterBlasterLaser