Add Item to GridLayoutGroup using Instantiate

Hi, I’m trying to add items to a grid using instantiate. The items are getting added and are positioned correctly;however, I can’t see the items. If I drag the prefab onto the grid in the editor at runtime it works fine, but using this code below the items are not visible.

private Vector3 autoLocalScale;
[SerializeField]
private GridLayoutGroup Grid;

//Init variables
void Start( )
{
  autoLocalScale = new Vector3( 1, 1, 1 );
}

public void AddItem( GameObject item )
{
        if ( item == null || item.GetComponent<TeamSelectItem>() == null )
            return;

        item.transform.SetParent( Grid.transform );
        item.transform.localScale = autoLocalScale;
        item.transform.localPosition = Vector3.zero;
}

item.transform.localScale = new Vector3( 1.0f, 1.0f, 1.0f );

Fixed it

By default the SetParent function tries to maintain the same world position the object had before gaining its new parent. It’s the same behavior the Unity editor has when you drag an object to a new parent in the Scene Hierarchy.

While your solution works, a more optimized approach is to tell Unity you don’t desire this behavior.
Use

item.transform.SetParent( Grid.transform, false );

item.transform.localScale = new Vector3( 1.0f, 1.0f, 1.0f );

Fixed it