Search Unity

Getting component in children bug

Discussion in 'Scripting' started by zoran404, Jul 28, 2015.

  1. zoran404

    zoran404

    Joined:
    Jan 11, 2015
    Posts:
    520
    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

    Code (csharp):
    1. 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?
     
  2. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    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.
     
  3. martinmr

    martinmr

    Joined:
    Mar 25, 2015
    Posts:
    325
    Yep same here, GetComponentsInChildren< >(); also returns the Parent gameobjects script, as long as the parent hast the same Script you are looking for
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    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
     
  5. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860

    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.
     
  6. zoran404

    zoran404

    Joined:
    Jan 11, 2015
    Posts:
    520
    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.
     
  7. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Time for a bug report. It should work.
     
  8. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Are the game objects active?
     
    Kiwasi likes this.
  9. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    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.