Search Unity

Iterating through GameObjects in Resources

Discussion in 'Scripting' started by CoffeeConundrum, May 20, 2015.

  1. CoffeeConundrum

    CoffeeConundrum

    Joined:
    Dec 30, 2013
    Posts:
    46
    I've been creating a level loader where I can load in the next section of the game into the current scene for a new project I'm working on.

    What I would like to do would be to use the Resources.FindObjectsOfType(typeof(GameObject)) and iterate through these in turn to check if they have the tag of level.

    After looking at the documentation for the function call, I found a JS example of how to iterate through them but no C#.

    Could anyone help out with translating this over to C# or have any examples of how to iterate through the results. Many thanks

    Code (JavaScript):
    1. import System.Collections.Generic;
    2.  
    3. // This script finds all the objects in scene, excluding prefabs:
    4. function GetAllObjectsInScene(): List.<GameObject> {
    5.     var objectsInScene: List.<GameObject> = new List.<GameObject>();
    6.    
    7.     for (var go: GameObject in Resources.FindObjectsOfTypeAll.<GameObject>()) {
    8.         if (go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave)
    9.             continue;
    10.        
    11.         var assetPath: String = AssetDatabase.GetAssetPath(go.transform.root.gameObject);
    12.         if (!String.IsNullOrEmpty(assetPath))
    13.             continue;
    14.        
    15.         objectsInScene.Add(go);
    16.     }
    17.    
    18.     return objectsInScene;
    19. }
     
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    3,755
    Something like this

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections.Generic;
    3. using UnityEditor;
    4.  
    5. public class Example : MonoBehaviour
    6. {
    7.     public List<GameObject> GetAllObjectsInScene()
    8.     {
    9.         List<GameObject> objectsInScene = new List<GameObject>();
    10.         foreach( var go in Resources.FindObjectsOfTypeAll<GameObject>() )
    11.         {
    12.             if( go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave )
    13.                 continue;
    14.  
    15.             var assetPath = AssetDatabase.GetAssetPath( go.transform.root.gameObject );
    16.             if( !string.IsNullOrEmpty( assetPath ) )
    17.                 continue;
    18.  
    19.             objectsInScene.Add( go );
    20.         }
    21.         return objectsInScene;
    22.     }
    23. }
     
unityunity