Generate specific number of InputFields via code?

46 views Asked by At

I have a GUI with 1 Input Field. When the user types in a number in there, for instance, "3", it has to generate 3 input fields within my canvas, so he can select the name of each player.

Any tips on how I could achieve such thing? Thanks!

1

There are 1 answers

0
peterept On

Add a game object to your canvas and add the "vertical list group" component to it. (Turn off child force expand so it doesn't resize your children). Now any children with "Layout element" component will be auto-positioned and sized for free.

So, now, one way is to create your input field, add the "layout element" component and set the min size. Then drag it into the project to make it a prefab.

Use the following code to create them:

void AddInputField(GameObject listGameObject, GameObject inputPrefab)
{
    RectTransform item = (RectTransform)Instantiate(inputPrefab);
    item.transform.SetParent(layoutController.transform, false);
    // Do stuff to setup item here
}