- Home /
Why doesn't childing a gameobject to GridLayoutGroup at runtime align it properly?
I'm trying to instantiate buttons inside of a grid layout group at runtime, and my assumption is that object.SetParent(grid,false) will automatically position each button with the correct cell spacing:
public GameObject buttonPrefab;
public override void MenuEnabled()
{
GridLayoutGroup myGridLayoutGroup = GetComponentInChildren<GridLayoutGroup>();
for (int i = 0; i < 5; i++)
{
GameObject tempObj = Instantiate(buttonPrefab, Vector3.zero, Quaternion.identity);
tempObj.transform.SetParent(myGridLayoutGroup.transform, false);
}
}
This all looks fine to me, and these objects do spawn and child themselves to my grid, but they don't align to its cells: every single button's local transform remains at vector3.zero. A quick google seems to show everyone else doing it the same way I am, is there some kind of initialization I'm missing which instructs the grid layout group to properly orient its new child?
I had similar issue, the thing that fixed it is to update a property like padding bottom to 1 and then back to 0. That would reset the grid and it's items to layout again.
That's so strange... changing the padding itself doesn't seem to work, you'd think if this were an intended part of the workflow, https://docs.unity3d.com/ScriptReference/UI.GridLayoutGroup.html would have some kind of public function to force the layout to update.
Well I posted an answer, it just needs to await moderation...
Answer by JustinEllis · Apr 06, 2017 at 07:24 PM
Well I currently have a grid layout and im also instantiating at runtime. This is what I have done:
My code looks like this:
GameObject NewFood = (GameObject)Instantiate(MainControl.instance.FoodItemPrefab, FoodItemsScrollView.transform, false);
The scrollview transform is the GameObject shown in the picture