Skip to content

Instantly share code, notes, and snippets.

Last active February 18, 2023 05:09
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Dynamically modify the size of the container of a vertical layout group.

Vertical Layout Group Dynamic Content

Dynamically modifies the size of the RectTransform of a VerticalLayoutGroup in Uniy. This component has to be attached to, for example, the Content GameObject of a ScrollView. If an new item is added to the container you must call the Adjust method to resize the RectTransform.

Unity Version

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
/// <summary>
/// Vertical Layout Group Dynamic Content.
/// <para>
/// Allows you to dynamically modify the size of the container of a vertical
/// layout group. Can be easily adapted to an horizontal layout group.
/// </para>
/// <para> By Javier García | @jvrgms | 2019 </para>
/// </summary>
[RequireComponent (typeof (VerticalLayoutGroup))]
public class VerticalLayoutGroupDynamicContent: UIBehaviour {
#region Class Members
VerticalLayoutGroup layoutGroup; // Layout group reference.
RectTransform rectTransform; // RectTransform of this GO.
#region Accessors
/// <summary> Gets the layout group. </summary>
/// <value> The layout group. </value>
public VerticalLayoutGroup LayoutGroup {
get {
if (layoutGroup != null)
return layoutGroup;
layoutGroup = GetComponent<VerticalLayoutGroup> ();
return layoutGroup;
/// <summary> Gets the rect transform. </summary>
/// <value> The rect transform. </value>
public RectTransform RectTransform {
get {
if (rectTransform != null)
return rectTransform;
rectTransform = GetComponent<RectTransform> ();
return rectTransform;
#region UI Behaviour Overrides
/// <summary> Called when the transform parent changed. </summary>
protected override void OnTransformParentChanged () {
Adjust ();
/// <summary> Called when the rect transform dimensions chenged. </summary>
protected override void OnRectTransformDimensionsChange () {
Adjust ();
#region Class Implementation
/// <summary> Adjust the size of the rect transform. </summary>
public void Adjust () {
// Set to zero if this instance does not have any child.
if (transform.childCount == 0) {
RectTransform.sizeDelta = new Vector2 (RectTransform.sizeDelta.x, 0);
float height;
int childCount = transform.childCount;
// Obtaning height size.
height = LayoutGroup.spacing * (childCount - 1);
height += LayoutGroup.padding.bottom;
height +=;
foreach (RectTransform child in transform)
height += child.sizeDelta.y;
// Applying height size.
RectTransform.sizeDelta = new Vector2 (RectTransform.sizeDelta.x, height);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment