- Home /
Dynamically added buttons aren't aligned in GridLayoutGroup
Hi everyone,
I guess this question has been asked many times already, but still, it's 2022 and it occurs :)
so basically, i made the following:
- A prefab of a simple button (so that I can later change the styles) 
- A panel called - BuildingMenufrom the UI library, which includes the- rid Layout Groupcomponent.
There's also a GAME game object added to the scene which includes a script called UIManager.
The issue rises, as soon as I try to dynamically add buttons to this grid, in which, with my expectations, the buttons should be aligned automatically, nice and easy.
the code is as follows:
 using Unity.VisualScripting;
 using UnityEngine;
 using UnityEngine.UI;
 
 public class UIManager : MonoBehaviour
 {
     private BuildingPlacer _buildingPlacer;
 
     public GameObject buildingMenu;
     public GameObject buildingButtonPrefab;
 
     private void Awake()
     {
         _buildingPlacer = GetComponent<BuildingPlacer>();
 
         for (var i = 0; i < Globals.BUILDING_DATA.Length; i++)
         {
             var button = Instantiate(
                 buildingButtonPrefab,
                 buildingMenu.transform,
                 false
             );
 
             var code = Globals.BUILDING_DATA[i].Code;
 
             button.name = code;
             button.transform.Find("Button").Find("Text").GetComponent<Text>().text = code;
 
             var b = button.transform.Find("Button").GetComponent<Button>();
             _AddBuildingButtonListener(b, i);
         }
         
         LayoutRebuilder.ForceRebuildLayoutImmediate(buildingMenu.GetComponent<RectTransform>());
     }
 
     private void _AddBuildingButtonListener(Button b, int i)
     {
         b.onClick.AddListener(() => _buildingPlacer.SelectPlacedBuilding(i));
     }
 }
Well, the buttons aren't aligned at all, and they don't even get shown in the scene. For this matter, I also added a 1-minute video showing my problem.
I appreciate any help.
Your answer
 
 
             Follow this Question
Related Questions
Grid layout group stretching text 1 Answer
Horizontal Layout Group making a Scroll Rect's Content rect width to be negative 1 Answer
Unity Check overlap of rect works except if in gridlayoutgroup 0 Answers
Create placeholders in grid layout group? 1 Answer
set child control size and child force expand on a grid layout 2 Answers
