As the title suggests, I'm trying to populate a UI panel with a GridLayoutGroup
component at runtime with sprites from the resources folder. The problem is that the sprites do not auto-align to the grid cells, instead getting drawn on the center of the panel.
I've tried the approach mentioned here but it does not work for me. Here is the script I've attached to the gui with the GridLayoutGroup
:
public class SpriteList : MonoBehaviour
{
public GameObject gridPanel;
public const string sortingLayer = "Foreground";
// Use this for initialization
void Start()
{
Sprite[] spriteArray = Resources.LoadAll<Sprite>("Sprites");
RectTransform gridRT = gridPanel.GetComponent<RectTransform>();
for (int i = 0; i < spriteArray.Length; i++)
{
GameObject cellObject = new GameObject();
cellObject.AddComponent<SpriteRenderer>();
cellObject.GetComponent<SpriteRenderer>().sprite = spriteArray[i];
cellObject.GetComponent<SpriteRenderer>().sortingLayerName = sortingLayer;
GameObject sprite = (GameObject) Instantiate(cellObject);
sprite.transform.SetParent(gridPanel.transform, false);
LayoutRebuilder.ForceRebuildLayoutImmediate(
gridPanel.GetComponent<RectTransform>());
sprite.transform.localScale = new Vector3(30, 30, 1);
}
}
Changing the settings of the GridLayoutGroup
do not modify the behaviour I'm seeing at all.
Since everything I see online seems to indicate that the key is the line
sprite.transform.SetParent(gridPanel.transform, false);
which I use, what am I missing?
Much gratitude!