Getting component in children bug

I’ve tried using GetComponentInChildren and GetComponentsInChildren, but neither one was returning the component in the child.

To get around this I accessed that child directly and got the component

buttonGameObject.transform.GetChild(0).gameObject.GetComponent<Text>();

As you can see I was getting the text of a button object.

Did anyone else notice this?

I had this issue too recently. Turns out getcomponentinchildren also will grab the component of the parent or the object the script is on if it has the same component type you’re looking for.

Yep same here, GetComponentsInChildren< >(); also returns the Parent gameobjects script, as long as the parent hast the same Script you are looking for

It’s not a bug, it’s by design and the docs explicitly tell you it does this. (Why by design, I don’t know; in my experience it’s annoying more often than it’s helpful.)

–Eric

I usually add a few extension methods to Component to give me the exact behaviour I wanted. Its worth doing if you find the built in methods aren’t sufficient for your needs. I inherited a project that used Transform.root everywhere. It needed to go in order for the new functionality I was building to work. So I replaced it with a GetComponentInParents method that traversed up the hierarchy looking for the correct component.

This has nothing to do with my problem.
The thing is that the function doesn’t find any of the components, even though there is one.

Time for a bug report. It should work.

Are the game objects active?

1 Like

Excellent question. Also, the script that’s been posted was the one that definitely works and isn’t a source of frustration. Please post the script that you used that failed to get the proper result instead, as that will be infinitely more useful.