Search code examples
c#unity-game-engineunity-ui

Unity GridLayoutGroup size problem with dynamically created cells


I want to populate GridLayoutGroup children dynamically from Prefab. Here is my GridLayoutGroup settings:

enter image description here

Here is code for my dynamically creating cells:

for (int i = 0; i < formSkins.Count; i++)
{
    GameObject skinElement = Instantiate(prifabSkinElemet, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);
    skinElement.transform.SetParent(skinElementParent.transform);
} 

And here is what I get as a result:

enter image description here

But when I add Prefab component (cells) by drag and drop into the GridLayoutGroup element, I get what I wanted and what I expected it to be:

enter image description here

Can someone tell me why when dynamically creating child's size not match as when I drag and drop?


Solution

  • Transform.SetParent

    public void SetParent(Transform parent, bool worldPositionStays);
    

    worldPositionStays: If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.

    So using transform.SetParent(x, false) will reset its position, scale, and rotation.