How do I space out UI elements evenly in a horizontal layout group?
Alright so I've been messing around with this for a while, and as far as I can see my math is correct, but the results are not as expected. I'm trying to adapt the spacing in a horizontal layout group to fit as many elements in there as possible. The numbers going in and out are correct, yet visually it looks wrong.
Here's the code:
HorizontalLayoutGroup group = NoticeContainer.GetComponent<HorizontalLayoutGroup>();
int childCount = NoticeContainer.transform.childCount;
if (childCount <= 0)
return;
float containerWidth = gameObject.GetComponent<RectTransform>().rect.width - 20; //-20 for padding
float childrenWidth = 0;
foreach (NoticeBoardButton child in NoticeContainer.GetComponentsInChildren<NoticeBoardButton>())
childrenWidth += child.gameObject.GetComponent<RectTransform>().rect.width;
//-47 is just for looks, it does not affect the result
if (childrenWidth + (-47 * childCount) > containerWidth)
group.spacing = ((containerWidth - childrenWidth) / childCount);
So for instance, right now I have 14 elements in the layout group. Each of them has 110 in width. The total width of all the children results to 1540 and the total container width is 680. The resulting padding from the calculation is -61.42857. If we take the resulting padding and multiply it by the amount of elemets (-61.42857 * 14) we get almost exactly -860. The total width of all children (1540) minus 860 is exactly 680. So the math is all correct, yet this is the visual result:
For some reason, the spacing subtraction is not sufficient. I've tried adding hardcoded values to see if I can make up for it, but the results are very strange and inconsistent. Any help on this matter would be great.
Thanks in advance!
Answer by ihearcolors · May 19 at 04:32 PM
Have you tried using a scroll bar? It just looks like there isn't enough room to show all of the cards.
Your answer
Follow this Question
Related Questions
Spawn Objects on Grid - how to define size? 1 Answer
Get CharacterInfo in the Editor? 1 Answer
Position object over center of cell of Grid Layout Group 0 Answers
Liquid layout - grid layout Group 0 Answers
¿Como puedo hacer un Grid como Editor solo con ciertas medidas en 2D? (Como Geometry Dash) 0 Answers