Search Unity

Resolved GetComponentsInChildren Not Working As Expected

Discussion in 'Scripting' started by Sooly890, Apr 21, 2023.

  1. Sooly890

    Sooly890

    Joined:
    Aug 24, 2022
    Posts:
    107
    So it's only outputting the parent. I actually want this, but it's not outputting the children:
    upload_2023-4-21_19-14-15.png
    I'm using unity 2018.2.10f1. But it should be exactly the same in this case.
    Code:
    Code (CSharp):
    1. foreach(Transform obj in meshUI[0].GetComponentsInChildren<Transform>())
    2.             {
    3.                 obj.gameObject.SetActive(true);
    4.                 Debug.Log(obj.name);
    5.             }
    What am I doing wrong?
    EDIT: sorry I forgot some info: where is says meshUI[0] that is just the GameObject PN Settings
     
    Last edited: Apr 21, 2023
  2. Yuchen_Chang

    Yuchen_Chang

    Joined:
    Apr 24, 2020
    Posts:
    127
    is your object originally inactive?
    GetComponentsInChildren()
    won't search inactive GameObjects. You will need
    GetComponentsInChildren<Transform>(true)
    to include inactive children.

    Take a look at the documentation of GetComponentsInChildren().
     
    Bunny83 likes this.
  3. Sooly890

    Sooly890

    Joined:
    Aug 24, 2022
    Posts:
    107
    ah, yes. that'll be why
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,736
    Keep in mind that using GetComponent<T>() and its kin (in Children, in Parent, etc) to try and tease out Components at runtime is definitely super-duper-uber-crazy-Ninja advanced stuff, to be avoided at all costs unless you know exactly what you are doing.

    If you run into an issue with any of these calls, start with the documentation to understand why.

    There is a clear set of extremely-well-defined conditions required for each of these calls to work, as well as definitions of what will and will not be returned.

    In the case of collections of Components, the order will NEVER be guaranteed, even if you happen to notice it is always in a particular order on your machine.

    It is ALWAYS better to go The Unity Way(tm) and make dedicated public fields and drag in the references you want.