How to add UI toggles dynamic to a canvas?

I have a database which contains game items that a user owns. I want to get that list through a php script and then display them with a ui toggle in a canvas element.The user shall be able to select what he wants and then click on a button. When the button is clicked then I want to know which toggles/items were selected. Each item has an ID from the database.

So I have 3 questions:

  1. How can I add such toggles dynamiclly on the canvas?
  2. How can I add to each one the ID from the Database
  3. How can I read which ID was selected when the user clicks the final button

Here is how I handle this.

GameObject addedChild = (GameObject)Instantiate(togglePrefab);
addedChild.transform.SetParent(toggleContainer);

Text text = addedChild.GetComponentInChildren<Text>();
text.text = displayedTitle;

Toggle toggle = addedChild.GetComponent<Toggle>();
toggle.onValueChanged.AddListener((bool toggled) =>
{
  PlayerSelectedToggle(itemID, toggled ? 1.0f : 0);
});

When I have more than one text component in my prefab, how can I difference them?

How can I find the toggleContainer? Is this my canvas or my panel in the canvas?

You might want to just create a script on the prefab that holds public references to the text and toggle components you need, then get that component. toggleContainer is any RectTransform but you probably want to put these under a scrollrect.

Thank you so far I managed to create my dynamic Lines and yes I want to put it in a scrollrect. This gives me some headaches right now. I managed to find my Canvas and use this in SetParents. So far so good. Now I tried to change it to a scrollrect. I found a tutorial for this, I use a panel added the scroll script to it and gave it a name. Now I tried to find that panel with my script and use this as parent. But I don’t manage that. So far I have this now:

GameObject ScrollViewPanel ;
GameObject [] Scrollpanels = FindObjectsOfType<GameObject>();
        foreach (GameObject Scrollpanel in Scrollpanels)
        {
           
            if(Scrollpanel.name == "MyScrollViewPanel")
            {

                ScrollViewPanel = Scrollpanel;
                break;
            }
        }

and some lines later I try to use this as parent with:

Line.transform.SetParent(ScrollViewPanel.transform);

But the compiler says that
"Use of unassigned local variable ScrollViewPanel " and “UnityEngine.Transform.SetParent(UnityEngine.Transform)’ has some invalid arguments”

How else can I find the scroll panel so that it can be the parent of my dynamic toggle Lines?

That code looks scary. :stuck_out_tongue: You should only need a single ScrollRect to group all of the toggles. Check out the UI Samples for how to set these up. You can also just create a public variable for the ScrollRect’s content GameObject and use the inspector to set it.

 public RectTransform toggleContainer;