Join the Discord. Talk about Game Dev. Talk about Gaming.
If you’ve ever wanted to get all of the children attached to a Unity GameObject and turn them into an array, there is a simple way to do it. I did this a number of times with my game Puzzledorf, for example with the UI, getting all of the buttons that were children of a menu.
The following code gets the jobs done in C#.
Transform[] allChildren = GetComponentsInChildren<Transform>(); foreach (Transform child in allChildren) { child.gameObject.SetActive(false); }
Since each child has a Transform component, this code will get all of the children and convert them into an array of Transforms. It will then loop through the array and deactivate them all. Read more about foreach loops here.
Although it’s an array of transforms, you can see from the loop it’s easy to access the GameObject. If you wanted a list of GameObjects rather than Transforms, you could improve the code thus:
Transform[] allChildren = GetComponentsInChildren<Transform>(); List<GameObject> childObjects = new List<GameObject>(); foreach (Transform child in allChildren) { childObjects.Add(child.gameObject); }
Thanks for the post. This will definitely come in handy.
LikeLiked by 2 people
No worries 🙂 Look forward to more helpful tips!
LikeLike