Search Unity

Finding inactive GameObject(s) instantiated during runtime after SetActive(false).

Discussion in 'Scripting' started by JackofTraes, Apr 4, 2018.

  1. JackofTraes

    JackofTraes

    Joined:
    May 28, 2014
    Posts:
    10
    Hello all!

    I have run into this problem a whole lot and up until now, I've been using object pooling and manually assigning objects using the inspector (public/serialized). There are many other posted methods but all of them, including the aforementioned, require much more effort than it's worth (especially if using SetActive() toggling on a large amount of game objects throughout the course of the game. After reading countless posts on these different solutions, I found a wish list reply by a user named chomp and it lead me to an easy workaround for those that wish to simply enable/disable instantiated game objects during runtime without writing or pasting large chunks of code. First, get a reference to the parent of the instantiated object(s) and then follow the code below (C#):

    Code (CSharp):
    1. GameObject parent; // You can also use a Transform reference directly.
    2.  
    3. // Find all children (inactive or otherwise).
    4. foreach (Transform child in parent.transform) {
    5.     if (!child.activeSelf) {
    6.         Debug.Log(child.name + " is inactive");
    7.     }
    8.     // You can now manipulate all children on the parent based on your game during runtime.
    9. }
    This method should also work for native game objects that are children to another game object. It will definitely work for instantiating UI objects with layout groups. Hopefully this helps someone!

    Note: If anyone has any other alternate quick solutions, please post them below.