GetComponent not working on GridLayoutGroup

I have this little script that is supposed to take a UIObjects RectTransform height (works) and then divide it by 5 and make it the cell size for the GridLayoutGroup (not working).

This is my code:

public GameObject gridLayout;
private float newCellSize;
void Update () {
	newCellSize = gridLayout.GetComponent<RectTransform>().rect.height/5;
	gridLayout.GetComponent<GridLayoutGroup>().cellSize = new Vector2(newCellSize, newCellSize);
}

For some reason my script isn’t recognizing the GridLayoutGroup component (before I even run my script). I have linked the gameObject in the inspector window. Thanks in advance!

The class GridLayoutGroup is defined in the UI namespace. To access it you have to either:

  • Add a using UnityEngine.UI; at the top of your script
  • directly specify the full qualified class name GetComponent<UnityEngine.UI.GridLayoutGroup>()

If you use multiple things from the UI namespace, the first solution is the usual one.

Sorry, seems like I had to inherit from UnityEngine.UI by adding using UnityEngine.UI;