A question about instantiation

Hello . I want to create a dynamic UI list in the script.
That is, to define an object for the list, another object for the rows in the list, and other objects for the row in the list such as Title, Description, Quantity, etc.

The question is how can I access this title, description, quantity to change their text without using “GetChild”.

    public GameObject GameObject_List;
    public GameObject Item_Template;

    public Text Title;
    public Text Desc;
    public Text Amount;

    int listItemsNumber = 5;

    void Start()

    {
        for (int i = 0; i < listItemsNumber; i++)
        {
            GameObject Item;
            Item = Instantiate(Item_Template, GameObject_List.transform);
            // Item.transform.GetChild(0).GetComponent<Text>().text = "Nr: " + i;

        }
        Destroy(Item_Template);
    }

is there a solution???

It’s actually pretty simple, you can get the child component via the GetComponentInChildren<T>() method.

Though, since you need to set multiple informations, a better approach would be to create a component on the Item_Template prefab that holds references for the various texts and has a utility method to assign the desired values. Then you instantiate that prefab and call said method.


##Example

This one is the utility class that goes onto the Item_Template’s prefab.

public class ListItemDisplayer : UIBehaviour {
    [SerializeField] private Text titleText;
    [SerializeField] private Text descriptionText;
    [SerializeField] private Text amountText;

    public void SetDisplayTexts(string title, string description, int amount) {
        titleText.text = title;
        descriptionText.text = description;
        amountText.text = $"{amount}";
    }
}

This one would be your other class:

[SerializeField] private ListItemDisplayer itemTemplatePrefab;
[SerializeField] private Transform listContainer;

[...]
var item = Instantiate(itemTemplatePrefab, listContainer);
// Since the object being instantiated is of type ListItemDisplayer, 
// the Instantiate function will return the object already casted
// therefore the public methods can be accessed directly without manually casting
item.SetDisplayText("Title here...", "Description here...", i);
[...]

I hope this is clear enough. If you don’t know what a prefab is or how to use it, try taking a look at Unity’s documentation for it.