Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Useful Method Extensions: transform.GetChildren, gameObject.GetChildren, gameObject.FindChild

Discussion in 'Scripting' started by Firedan1176, Feb 18, 2015.

  1. Firedan1176

    Firedan1176

    Joined:
    Dec 7, 2013
    Posts:
    48
    I know that something like this is redundant (and maybe this has been posted before), but I made 3 extremely simple but useful method extensions for transform and gameObject.

    You can grab all the children and put them into an array either as transforms or gameObjects (which in itself is also redundant), and you can also find a child of a gameObject.

    Syntax:
    Code (CSharp):
    1. GameObject[] childrenObjects;
    2.  
    3. void Start() {
    4. childrenObjects = gameObject.GetChildren();
    5. }
    Or transform is simply the opposite:

    Code (CSharp):
    1. Transform[] childrenObjects;
    2. void Start() {
    3. childrenObjects = transform.GetChildren();
    4. }

    If you want to get a child by name, you can use:

    Code (CSharp):
    1. void Start() {
    2. GameObject someChild = gameObject.FindChild("Random name of child (Clone)");
    3. }

    Again, these are redundant but useful to use less code.
     

    Attached Files:

  2. jtsmith1287

    jtsmith1287

    Joined:
    Aug 3, 2014
    Posts:
    787
    What happens if you add a chile at runtime? What's going to add it to the array? Are you going to generate a new array or use a list at that point?
     
  3. Firedan1176

    Firedan1176

    Joined:
    Dec 7, 2013
    Posts:
    48
    Well you can call it at any point. Even during runtime all it does is create an array based off of the children, in the order in the heirarchy. So if my order is:

    It will show up in that order in the array.