How add texts to scrollrect at runtime

I’m create panel for scrolling text objects. Texts instantiate runtime from prefab. I have hierarchy

Content object has attached component VerticalLayoutGroup. Code for adding texts

            for (int i = 0; i < 10; i++)
            {
                GameObject inst = (GameObject)Instantiate(textPrefab);
                inst.GetComponent<Text>().text = contentString;

                inst.transform.SetParent(layoutGroup.transform, false);
            }

Result view:

Texts don’t wrap horizontally and VerticalLayoutGroup rect don’t fit to texts sizes.
But i need get view something like this

Describe steps for creating dinamically added texts to scroll, please

Some things I’d check:

  • Make sure the text prefab has the Horizontal Overflow field set to “Wrap”
  • Are you using a ContentSizeFitter on the VerticalLayoutGroup? Make sure that is set to “Unconstrained” on the horizontal axis so it doesn’t resize to the preferred size of the text. (Also make sure the VerticalLayoutGroup RectTransform is constrained to stretch to fit the parent horizontally.)

Thanks, on Text Prefab in component LayoutElement set check on ‘Min Width’ and enter some value, on VerticalLayoutGroup->ContentSizeFitter set ‘Horizontal Fit’ = ‘Unconstrained’, ‘Vertical Fit’ = ‘Preferred Size’. With this settings height of text and rect size computed automatically

1 Like