How to get component of gameobjects in a list
Hello ppl. I have this script to add my selected gameobjects to a list (in runtime).
public Transform ParentOfList;
public List<GameObject> Objects3d = new List<GameObject>();
public GameObject ActualSelected;
public void add3DtoList()
{
foreach (Transform child in ParentOfList) // iterate through all first level children
{
if (child.gameObject.activeSelf)
{
Debug.Log($"The child {child.name} is active!");
ActualSelected = child.gameObject;
if (Objects3d.Contains(ActualSelected))
{
Debug.Log("Already exist in list");
}
else
{
Objects3d.Add(ActualSelected); //add the actual gameobject highlighted to list
}
}
}
}
Now I want to get the text component of all the objects added to the list and store together in a new text variable. is possible?. I get the text component of a gameobject with this: GetComponent<Text>().text;
but don't know how implement it in a list. Some guidance?, thanks.
SOLVED.
Answer by elfasito · Sep 01, 2020 at 03:50 PM
script solution:
public Transform ParentOfList;
public List<GameObject> Objects3d = new List<GameObject>();
public GameObject ActualSelected;
public Text MergeText;
public void add3DtoList()
{
foreach (Transform child in ParentOfList) // iterate through all first level children
{
if (child.gameObject.activeSelf)
{
Debug.Log($"The child {child.name} is active!");
ActualSelected = child.gameObject;
if (Objects3d.Contains(ActualSelected))
{
Debug.Log("Already exist in list");
}
else
{
Objects3d.Add(ActualSelected); //add the actual gameobject selected to list
}
}
}
MergeText.text = string.Join("\n", Objects3d.Select(obj => obj.GetComponent<Text>().text));
}
Answer by xxmariofer · Sep 01, 2020 at 01:42 PM
public Transform ParentOfList;
public List<GameObject> Objects3d = new List<GameObject>();
public GameObject ActualSelected;
public Text newTextVariable;
public void add3DtoList()
{
string text = "";
foreach (Transform child in ParentOfList) // iterate through all first level children
{
if (child.gameObject.activeSelf)
{
Debug.Log($"The child {child.name} is active!");
ActualSelected = child.gameObject;
if (Objects3d.Contains(ActualSelected))
{
Debug.Log("Already exist in list");
}
else
{
Objects3d.Add(ActualSelected); //add the actual gameobject highlighted to list
text += ActualSelected.gameObject.GetComponent<Text>().text;
}
}
newTextVariable.text = text;
}
}
Hello @xxmariofer , thanks for your reply. I tested your code modification, If im not doing something wrong, the Text newTextVariable
show me the last text compoment I added to my list, can be?. I want It show me the text component of all my gameobjects added to the list in a new text variable. like: newTextVariable = ListIndex1.text + ListIndex2.text + etc;