johnhattan icon

FindGameObjectsWithTag that can check inactive objects

johnhattan | PRO | 04/18/17 06:58:45 PM UTC | 0 ⭐ | 313 👁️ | Never ⏰ | []
C# |

790 B

|

None

|

0 👍

/

0 👎

// note, this is not very efficient, as evidenced by the three levels of looping required.
// If you call this every frame, you will not be a happy person.
 
public static class GameObjectHelpers
{
    public static GameObject[] FindGameObjectsWithTag(string tag, bool activesOnly = true)
    {
        if(activesOnly)
            return GameObject.FindGameObjectsWithTag(tag);
        else
        {
            List<GameObject> RetVal = new List<GameObject>();
 
            for(int i = SceneManager.sceneCount - 1; i >= 0; --i)
            {
                var Scene = SceneManager.GetSceneAt(i);
                if(Scene.isLoaded)
                    foreach(var RootGO in Scene.GetRootGameObjects())
                        foreach(var T in RootGO.GetComponentsInChildren<Transform>(true))
                            if(T.CompareTag(tag))
                                RetVal.Add(T.gameObject);
            }
 
            return RetVal.ToArray();
        }
    }
}

Comments