Unity snippet: Finding a GameObject by name, even inactive or disabled ones

I use GameObject.Find() in Unity for things like enabling or fading in/out a menu or to grab an object reference via code to store for later.   (I usually prefer doing things in code rather than drag and dropping references using the Unity Editor when I can)

A problem is GameObject.Find() won’t locate inactive gameobjects which causes me problems because I tend to have inactive object trees in a scene that are just turned on/off when they are being used, like a GUI menu for example.  It’s just kind of my programming style to do things that way.

I couldn’t find a clean full snippet for this online that used scene.GetRootGameObjects, so figured I’d post one.

Cut and paste this to MyUtils.cs or your own utils class:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MyUtils 
{

    //hideously slow as it iterates all objects, so don't overuse!
    public static GameObject FindInChildrenIncludingInactive(GameObject go, string name)
    {

        for (int i = 0; i < go.transform.childCount; i++)
        {
            if (go.transform.GetChild(i).gameObject.name == name) return go.transform.GetChild(i).gameObject;
            GameObject found = FindInChildrenIncludingInactive(go.transform.GetChild(i).gameObject, name);
            if (found != null) return found;
        }

        return null;  //couldn't find crap
    }

    //hideously slow as it iterates all objects, so don't overuse!
    public static GameObject FindIncludingInactive(string name)
    {
        Scene scene = SceneManager.GetActiveScene();
        var game_objects = new List();
        scene.GetRootGameObjects(game_objects);

        foreach (GameObject obj in game_objects)
        {
            GameObject found = FindInChildrenIncludingInactive(obj, name);
            if (found) return found;
        }

        return null;
    }

}

And use it from anywhere like:

GameObject obj = MyUtil.FindIncludingInactive(“MyMenuName”);

Leave a Reply

Your email address will not be published. Required fields are marked *