johnhattan

FindGameObjectsWithTag that can check inactive objects

Apr 18th, 2017
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.79 KB | None | 0 0
  1. // note, this is not very efficient, as evidenced by the three levels of looping required.
  2. // If you call this every frame, you will not be a happy person.
  3.  
  4. public static class GameObjectHelpers
  5. {
  6.     public static GameObject[] FindGameObjectsWithTag(string tag, bool activesOnly = true)
  7.     {
  8.         if(activesOnly)
  9.             return GameObject.FindGameObjectsWithTag(tag);
  10.         else
  11.         {
  12.             List<GameObject> RetVal = new List<GameObject>();
  13.  
  14.             for(int i = SceneManager.sceneCount - 1; i >= 0; --i)
  15.             {
  16.                 var Scene = SceneManager.GetSceneAt(i);
  17.                 if(Scene.isLoaded)
  18.                     foreach(var RootGO in Scene.GetRootGameObjects())
  19.                         foreach(var T in RootGO.GetComponentsInChildren<Transform>(true))
  20.                             if(T.CompareTag(tag))
  21.                                 RetVal.Add(T.gameObject);
  22.             }
  23.  
  24.             return RetVal.ToArray();
  25.         }
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment