I have a panel in my canvas.
I’ve added the content size fitter script.
In this panel I will instantiate prefabs (which are also panels, that represent level boxes)
With this code
GameObject levelBox = Resources.Load < GameObject > ("Prefabs/Level Box");
int y = 0;
for (int i = 1; i <= 10; i++) {
GameObject a = (GameObject) Instantiate(levelBox);
a.transform.SetParent(transform, false);
RectTransform rectTransform = a.GetComponent < RectTransform > ();
rectTransform.anchoredPosition = new Vector2(0, y);
y -= 300;
}
The problem is that the panel won’t change its size to fit all the child objects.
I need to do this, because the panel parent has a Scroll Rect.
How it looks at runtime:
Mark the parent panel RectTransform as needing it’s layout to be recalculated during the next layout pass.
LayoutRebuilder.MarkLayoutForRebuild(this.transform as RectTransform);
Add layout element component to lvlpanels or add grid/vertical/horizontal layout to that content fitter panel.