The question is answered, right answer was accepted
Easy way to find all types attached to gameobject parent when there are like 10 or more childen/children/children etc?
Hello,
I have randomly generating spaceships and stations and I need to be able to easily find all types attached to the highest parents transform.
Is it possible to iterate or something without writing 100 lines of iterations of foreach loops? EG:
for (int i = 0; i < gameObject.transform.childCount; i++)
{
if (transform.GetChild(i).gameObject.GetComponent<Weapon>())
{
weaponModulesList.Add(transform.GetChild(i).gameObject.GetComponent<Weapon>());
}
if (gameObject.transform.GetChild(i).childCount > 0)
{
for (int ii = 0; ii < gameObject.transform.GetChild(i).childCount; ii++)
{
if (transform.GetChild(i).gameObject.transform.GetChild(ii).gameObject.GetComponent<Weapon>())
{
weaponModulesList.Add(transform.GetChild(i).gameObject.transform.GetChild(ii).gameObject.GetComponent<Weapon>());
}
if (gameObject.transform.GetChild(i).GetChild(ii).childCount > 0)
{
for (int iii = 0; iii < gameObject.transform.GetChild(i).GetChild(ii).childCount; iii++)
{
if (transform.GetChild(i).gameObject.transform.GetChild(ii).gameObject.gameObject.transform.GetChild(iii).GetComponent<Weapon>())
{
weaponModulesList.Add(transform.GetChild(i).gameObject.transform.GetChild(ii).gameObject.gameObject.transform.GetChild(iii).GetComponent<Weapon>());
}
}
}
}
}
}
Do I have to do this 100 times or is there a better and quicker way? Please help?
Answer by PizzaPie · Jun 11, 2017 at 05:20 PM
If you mean to get all Weapon Components you may use
Weapon[] myWeaponArray = parentGameObject.GetComponentsInChildren<Weapon>();
This will return also Weapon Type components from parent Object too.
Follow this Question
Related Questions
Destroy one child (of same instance) after another? 0 Answers
Looking through all the children doesn't work 1 Answer
Array[] of children of a child 3 Answers
Destroyng all childs of an object 1 Answer
How to assign a child of a prefab 1 Answer