Home > Back-end >  How to get the List of the child of a parent game object and get their names
How to get the List of the child of a parent game object and get their names

Time:10-08

I am a beginner in Unity and I am currently making a simple game. I have a problem where I want to get the children of a parent object and put it in a list. I want to at least get the name of the children objects. And I want to know how to get the name of a specific object in the list, for example I have three buttons with names button1, button2, and button3. I want to get the name of the button3 only. And last how can I get the objects from the list randomly and output their name in Debug.Log() or set their name in the 3 textboxes randomly.

This is the script that I currently have.

// THE LIST OF BUTTONS FOR THE CHILDREN OF THE PARENT GAME OBJECT
[SerializeField] List<Button> childrenObject;
private GameObject parentObject;

// COMMONLY I HAVE 3 TEXTBOXES
// THIS TEXTBOXES HAVE A PARENT TOO
[SerializeField] List<TextMeshProUGUI> textBoxes;

public void methodName()
{
    // GET THE NAME OF THE CHILDREN IN THE LIST
    // GET THE NAME OF A SPECIFIC OBJECT IN THE LIST
    // GET THEIR NAME RANDOMLY AND SET THEIR NAME IN THE BOX IN THE LIST
}

CodePudding user response:

i assume the text boxes are inside of buttons, try something like

// THE LIST OF BUTTONS FOR THE CHILDREN OF THE PARENT GAME OBJECT
[SerializeField] List<Button> childrenObject;
private GameObject parentObject;

// COMMONLY I HAVE 3 TEXTBOXES
// THIS TEXTBOXES HAVE A PARENT TOO
[SerializeField] List<TextMeshProUGUI> textBoxes;

public void methodName()
{
childrenObject = parentObject.GetComponentsInChildren<Button>();
for(int i = 0; i < childrenObject.Count; i  )
{
 textBoxes.Add(chidrenObject[i].GetComponentInChildren<TextMeshProUGUI>());
}
}

CodePudding user response:

I solved my problem using Transform.

The choices and v1 GameObject is the parent of the children that I wanted to get.

[SerializeField] GameObject choices, v1, finishPanel;

// RANDOM NUMBER HOLDER FOR CHECKING
private int randomNumber, foundCount;
// RANDOMIZED NUMBER LIST HOLDER
public List<int> RndmList = new List<int>();

This is the process where I randomized numbers and those numbers indicates the indexes of the children of each parent.

private void Awake()
{
    foundCount = 0;
    RndmList = new List<int>(new int[v1.transform.childCount]);

    for (int i = 0; i < v1.transform.childCount; i  )
    {
        randomNumber = UnityEngine.Random.Range(0, (v1.transform.childCount)   1);
        while (RndmList.Contains(randomNumber))
        {
            randomNumber = UnityEngine.Random.Range(0, (v1.transform.childCount)   1);
        }
        RndmList[i] = randomNumber;
        // Debug.Log(v1.transform.GetChild(randomNumber-1).name);
        choices.transform.GetChild(i).GetComponentInChildren<TextMeshProUGUI>().text = v1.transform.GetChild(randomNumber - 1).name;
    }
}
  • Related