How can I make a ScrollRect adjust to the height of its child objects?

Hi everyone,

I’m currently working on a Unity project where I have a ScrollRect that contains a GridLayoutGroup with child objects that can be added or removed dynamically during gameplay. I want the Gameobject that contains the Grid layout group to adjust its height based on the height of the child objects inside the GridLayoutGroup, so that the user can scroll through all the items without any overflow.

Is there any way to achieve this? I’d appreciate any help or suggestions you could provide.

Thanks in advance!

This is something i’ve tried to use but it doesnt work.
Code (CSharp):

  • private GridLayoutGroup gridLayoutGroup;
  • private RectTransform rectTransform;
    • private void Awake()
  • {
  • gridLayoutGroup = GetComponent();
  • rectTransform = GetComponent();
  • }
    • private void OnTransformChildrenChanged()
  • {
  • // Calculate the height of the GridLayoutGroup based on its child items
  • float height = 0f;
  • foreach (RectTransform child in transform)
  • {
  • height += child.sizeDelta.y + gridLayoutGroup.spacing.y;
  • }
    • // Set the height of the parent rect transform to the height of the GridLayoutGroup
  • rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, height);
    • // Anchor the top edge of the GridLayoutGroup to its parent’s top edge
  • rectTransform.anchorMax = new Vector2(rectTransform.anchorMax.x, 1f);
  • rectTransform.anchorMin = new Vector2(rectTransform.anchorMin.x, 1f);
  • rectTransform.pivot = new Vector2(rectTransform.pivot.x, 1f);
  • rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, 0f);

The hierarchy looks like this.
Canvas >
Viewport - Component = Rect Mask 2d >
Content - Component = Grid layout group >
Item - Component = image.