Whats the correct way to access components of child dren or just children themselves of an object within a c# script.
My scenario :
I’m instantiating a list of objects at runtime for a menu and they are all given a parent object, but I’m not sure how to go about getting a specific child of that object to change things such as text components. Also how do I get a specific text object when there are more than one in an object?
I have a basic UI element that you can consider a button, that has multiple text objects that need to be dynamically updated. I instantiate these groups as the game goes to add new different buttons to the menu.
Hopefully that makes sense.
Panel (parent)
→ Panel a (button)
----> Text a
----> Text b
→ Panel b
----> Text a
----> Text b
How do I get text b of panel a specifically?
You should have a manager script that stores references to the instantiated UI componenets. The example below stores them in a List.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class UIManager : MonoBehaviour
{
[SerializeField]
private Button m_buttonPrefab;
private List<Button> m_buttons;
public void Start()
{
m_buttons = new List<Button>();
int noOfElements = 10;
for(int i = 0; i < noOfElements; i++)
{
Button button = GameObject.Instantiate(m_buttonPrefab);
button.transform.parent = transform;
m_buttons.Add(button);
}
}
}
When instantiating a component that has more than one of the same type underneath it, I would again have some kind of manager for that. For example; if you’re going to be instantiating Buttons that have multiple text component children, create a custom class that stores those pieces of texts;
public class MultiTextButton : Button
{
[SerializeField]
private Text[] m_texts;
public Text GetText(int p_id)
{
if (p_id < m_texts.Length)
return m_texts[p_id];
return null;
}
}
Hope this helped, let me know if I’ve misunderstood and I’ll update my solution accordingly.