[UI] How to force Content Size Fitter Update after instantiating a prefab?

Hi everyone,

I have a quite complexe interface with scroll rect and everything. All is ok BUT, when i instantiate a prefab in a parent which contains a content size fitter component, the size is not update until i enable/disable the game object in the editor.

I’ve already tried some weird coroutines with WaitForEndOfFrame(), then re-enable object, and other functions like :

LayoutRebuilder.MarkLayoutForRebuild(this.transform as RectTransform);

Nothing is working atm and i wonder why i can’t force the UI to redraw. Any ideas?

I’ve had the same problem and found a tricky workaround - changing the spacing of the layout group (even by as little as 0.01) forces the content size fitter to update. Just add & subtract 0.01 alternately every time you instantiate your prefab.

I tried this workaround and it works for me in unity 2021.3.6f1

        private void RefreshContentSize()
            System.Collections.IEnumerator Routine()
                var csf = this.root.GetComponent<ContentSizeFitter>();
                csf.verticalFit = ContentSizeFitter.FitMode.Unconstrained;
                yield return null;
                csf.verticalFit = ContentSizeFitter.FitMode.PreferredSize;

I call this function everytime I want the ContentSizeFitter (the “root” variable here) to be refreshed.