Skip to content

Instantly share code, notes, and snippets.

@JosephStar318
Last active February 25, 2026 12:46
Show Gist options
  • Select an option

  • Save JosephStar318/a88947c4327d087e85b7b0e78e604bfb to your computer and use it in GitHub Desktop.

Select an option

Save JosephStar318/a88947c4327d087e85b7b0e78e604bfb to your computer and use it in GitHub Desktop.
A Solution to Unity's annoying layout groups that doesn't update itself properly after any child state change. This script adds LayoutRebuilder script to the game object whenever you create a layout group in the inspector and update layout groups whenever needed at runtime
using System.Collections;
using UnityEngine;
[DisallowMultipleComponent]
public class LayoutRebuilder : MonoBehaviour
{
private bool marked = false;
private RectTransform _rectTransform;
public RectTransform rectTransform
{
get
{
if (_rectTransform == null)
{
_rectTransform = GetComponent<RectTransform>();
}
return _rectTransform;
}
}
private LayoutRebuilder _parentLayoutRebuilder;
IEnumerator Start()
{
if (transform.parent != null)
_parentLayoutRebuilder = transform.parent.GetComponentInParent<LayoutRebuilder>();
yield return null;
var _childLayoutRebuilders = GetComponentsInChildren<LayoutRebuilder>();
if (_childLayoutRebuilders.Length == 1)
{
UpdateLayout();
}
}
void OnTransformChildrenChanged()
{
UpdateLayout();
}
void OnChildRectTransformDimensionsChange()
{
UpdateLayout();
}
void OnCanvasGroupChanged()
{
UpdateLayout();
}
void OnRectTransformRemoved()
{
UpdateLayout();
}
void OnTransformParentChanged()
{
_parentLayoutRebuilder = GetComponentInParent<LayoutRebuilder>();
UpdateLayout();
}
void OnRectTransformDimensionsChange()
{
UpdateLayout();
}
public void UpdateLayout()
{
if (marked) return;
marked = true;
UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(rectTransform);
if (_parentLayoutRebuilder != null)
_parentLayoutRebuilder.UpdateLayout();
}
void Update()
{
if (marked)
marked = false;
}
}
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoad]
public static class LayoutRebuilderAutoAdder
{
static LayoutRebuilderAutoAdder()
{
UnityEditor.ObjectFactory.componentWasAdded -= OnComponentAdded;
UnityEditor.ObjectFactory.componentWasAdded += OnComponentAdded;
}
private static void OnComponentAdded(Component component)
{
if (component is UnityEngine.UI.LayoutGroup)
{
var go = component.gameObject;
if (!go.GetComponent<LayoutRebuilder>())
{
go.AddComponent<LayoutRebuilder>();
}
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment