Unity Community

Results 1 to 5 of 5

Thread: Get Child (C#)

  1. Posts

    Get Child (C#)

    Is there any way to access the children of an object directly?

  2. Posts
    try this:
    1. public class lol
    2. {
    4.     private Troll trololo;
    6.     void Start()
    7.     {
    8.         trololo = GetComponentInChildren<Troll>();
    9.     }
    10. }

    also see the reference here:

  3. Location
    Provo, Utah
    If you know the name of the child object, you can get its transform by doing a transform.FindChild("Child Name"). You can then get the child gameObject by calling .gameObject on the child's transform.

    1. GameObject childGO = transform.FindChild("Child Object").gameObject;

    This code will throw a null reference exception if "Child Object" does not exist, so it's probably better practice to store the child's transform in a temporary variable and make sure it isn't null before trying to get its gameObject.

  4. Posts
    finding and manipulating GameObjects based on their names or position in the transform hierarchy is generally discouraged, as explained here (a little more than 1/4 of the way through, but watch the whole thing if you haven't, it's great):

    most of the time doing it will lead to brittle code that not only can't be reused in future projects but has to be changed constantly during the project and often doesn't work because of a mistake made while using the inspector. it's more excusable if the names or hierarchies are created in code, but in that case you could store a reference to the children on creating or modifying them and access it later which would be a lot more efficient than FindChild or GetComponentInChildren. another exception i thought of is for scripts that manipulate character bones, like Rune's Head Look Controller and Locomotion System, but in that case public GameObject/Transform references are much easier and more flexible than getting the child objects in code.

    in short, there might be a more efficient and flexible way to accomplish whatever it is you want to, and we'd be able to help you figure it out with a little more information.
    Last edited by teatime; 03-28-2011 at 01:43 PM.

  5. Posts
    Well, what I'm trying to do is have a loading bar above a vehicle hanger to represent the progress of training a unit, like in pretty much any RTS game. I'd rather not assign the GUITexture i have for the loading bar to each hanger in the inspector as the player will be able to create more hangers throughout the game. I have the loading bar parented to my hanger prefab. Thus, I thought I could put a bit of code in my Start() function to assign the loading texture to a variable. The loading bar is actually two GUITextures, so using the type won't work.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts