- Home /
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;
}
I noticed that the item.transform.localScale is not actually setting the RectTransforms Scale... when I change it in the editor it fixed the issue. Is there a way to make this work in code?
Answer by CasualT · May 22, 2016 at 11:05 PM
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 );
Answer by vjb · Apr 08, 2015 at 12:11 AM
item.transform.localScale = new Vector3( 1.0f, 1.0f, 1.0f );
Fixed it
Answer by vjb · Apr 08, 2015 at 12:11 AM
item.transform.localScale = new Vector3( 1.0f, 1.0f, 1.0f );
Fixed it