Finding children of an object with a tag

I need to create a GameObject[ ] of every child of ‘root’ with a certain tag. This has turned out to be trickier than I expected- I can’t think of an easy way to search through only the children of an object for a tag (without searching through everything in the scene for tags, then filtering for the right parent). I’m still searching for an answer myself, but can anyone here suggest a good approach?

Thanks a lot for any help!

Just use CompareTag.

Something like this:

[SerializeField] new string tag;
[SerializeField] GameObject[] childrenWithTag;

[ContextMenu("Custom Reset")] void Reset () {
	List<GameObject> childrenWithTag = new List<GameObject>();
	foreach (Transform child in transform)
		if (child.CompareTag(tag)) childrenWithTag.Add(child.gameObject);
	this.childrenWithTag = childrenWithTag.ToArray();
}

Aha! I did not realize you could do a “foreach (Transform child in transform)”.

Thanks a lot!

They tried to tell you! :wink:

Wow, you are right about that! better be more observant.