- Home /
Acess 1st degree children and the same components in them and children inside of the children?
On player death i want to reset my enemies.
I have a parent object for my enemies. Inside, there are the prefab enemy copies with slightly different names - with a different number in the brackets.
I want to access (turn Off/On) some components of all of the enemies and 2 Game Objects (turn them on/off) that are children of the enemies for every one of them.
How exactly is the (preferably c#) code to do this?
Answer by KoenigX3 · Jan 16, 2017 at 10:37 PM
If you have an EnemyManager script which handles the spawning of the enemies, you should collect them into an array of GameObjects. For accessing the components of the enemies, you can use:
foreach(GameObject enemy in enemies)
{
enemy.GetComponent<Type>().enabled = false;
}
For accessing the children of the enemies, you can use:
foreach(GameObject enemy in enemies)
{
enemy.transform.GetChild(0).gameObject.SetActive(false);
enemy.transform.GetChild(1).gameObject.SetActive(false);
}
The 0 and 1 integer parameter represents the number of the child in the hierarchy (so 0 refers to the 1st child, 1 refers to the 2nd child, etc). The 'enemies' variable represent the GameObject array.
Answer by Arkaid · Jan 17, 2017 at 12:34 AM
If you're looking for specific components, just use GetComponentsInChildren. It's recursive, so it's going to find all the components inside that hierarchy.
For example, say that the component you want to turn off is called Enemy
, then you could do:
Enemy [] enemies = enemiesParent.GetComponentsInChildren<Enemy>();
foreach (Enemy enemy in enemies)
enemy.gameObject.SetActive(false);