Search code examples
unity-game-enginelayoutgameobject

Instantiate dynamically buttons on vertical layout group


I have the following hierarchy:

enter image description here

I want to instantiate dinamically Game Button into that Button Layout and make them look good.

I'm doing something like this:

public GameObject questionButton;

public void nextRound(){

    foreach (Question elem in questionList)
    {
        GameObject child = Instantiate(questionButton);
        child.transform.SetParent(questionButton.transform,false);
        child.GetComponent<Text>().text = elem.answer;
    }
}

But does not seem to work properly, it doens't get ordener with the layout:

enter image description here

How I can do that?


Solution

  • The line: child.transform.SetParent(questionButton.transform,false); Should be changed as you are setting the parent as the questionButton. You should be setting it as the layout group. So instead:

    public GameObject layoutGroup;
    ...
    child.transform.SetParent(layoutGroup.transform,false);