I’m trying to fill a grid with buttons (using UnityUI), but I want them to fill the entire screen, so I calculate it’s size on the fly.
I have an empty GameObject, child of the main Canvas, with a GridLayoutGroup component, and attached to it my script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CrearTablero: MonoBehaviour {
public int rows = 4;
public int columns = 4;
private int buttonWidth;
private int buttonHeight;
public Button prefab;
private Button button;
void Start () {
buttonHeight = Screen.height / rows;
buttonWidth = Screen.width / columns;
GridLayoutGroup grid = this.GetComponent<GridLayoutGroup> ();
grid.cellSize = new Vector2 (buttonWidth,buttonHeight);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
button = (Button)Instantiate(prefab);
button.transform.SetParent(transform);
}
}
}
}
With this I’ve tried to make the buttons childs of the Empty GameObject and, since they are childs of a GridLayoutGroup I expected them to appear arranged properly, but when I try it, this is what I get:
What am I doing wrong?