- Home /
Dynamically populate variable number of sprites on grid layout group
Hello.
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>();
GameObject cellObject = new GameObject();
cellObject.AddComponent<SpriteRenderer>();
for (int i = 0; i < spriteArray.Length; i++)
{
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
does 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?
Your answer
Follow this Question
Related Questions
How to create a GUI like Zombieville? 1 Answer
Unity 4.6 GUI at runtime! 1 Answer
Determining GUI button pressed 2 Answers
Gui Box - Texture - Spritesheet 0 Answers
detect mouseover with grid buttons? 1 Answer