Search Unity

How do I set a child if an object to inactive?

Discussion in 'Scripting' started by Nitrox32, Aug 14, 2017.

  1. Nitrox32

    Nitrox32

    Joined:
    May 9, 2017
    Posts:
    161
    How do I set a child of an object to inactive in C#? I'm a new to scripting so please provide an example. Thanks!
     
  2. cstooch

    cstooch

    Joined:
    Apr 16, 2014
    Posts:
    354
    Similar to how you'd set anything else to inactive. You'll need a reference to the child game object somehow. Your question is quite broad. So it's hard to answer. But if your script is on the parent, you need to find a reference to the child somehow. If the child is something that never changes, then I'd suggest setting this in the property inspector.. declare it something like so:
    Code (csharp):
    1. public Gameobject someGameObject;
    Then drag the child object onto this variable in the property inspector. If I'm currently speaking gibberish to you, then you will want to do some beginner tutorials, ASAP!

    Anyways, later on, do this:

    Code (csharp):
    1. someGameObject.SetActive(false);

    If your child object is not known to you at design time, then you might have to go find it in some way. There are functions for finding child objects by type and tag, and stuff.. I don't like those because they have more overhead... so if you can set the game object in the inspector, that's the best way.

    Hopefully that helps, if not, more details on the set up of your objects will probably be needed.
     
  3. Nitrox32

    Nitrox32

    Joined:
    May 9, 2017
    Posts:
    161
    Ha! That's perfect! I was making that way to hard with my method! Thanks!
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Transform.Find works if you know the name of the child. GetComponentInChildren works if you know the type. Failing both of these, Transform itself is also an enumerator, which will return all of the children. So worst case scenario you can do a search of all children.

    While none of these are as fast as a direct editor reference, they aren't especially slow either. I wouldn't worry about the performance cost.
     
    cstooch likes this.