Search Unity

Unit test for finding an object in all scenes

Discussion in 'Scripting' started by robloz, May 27, 2017.

  1. robloz

    robloz

    Joined:
    Apr 27, 2013
    Posts:
    10
    Hello, I am trying to make a test to check if an particular object is in all scenes in my project, in this case the object is Transition.
    However the current snippet won't iterate throw all scenes.
    I tried with SceneManager.sceneCount also but nothing. How can I do it?

    Code (CSharp):
    1. [Test]
    2. public void ObjectInAllScenes()
    3. {
    4.     var rootObjects = new List<GameObject>();
    5.  
    6.     for (int j = 0; j < SceneManager.sceneCountInBuildSettings; j++)
    7.     {
    8.         var isIn = false;
    9.         var scene = SceneManager.GetSceneAt(j);
    10.      
    11.         scene.GetRootGameObjects(rootObjects);
    12.  
    13.         for (int i = 0; i < rootObjects.Count && !isIn; ++i)
    14.         {
    15.             if (rootObjects[i].name == "Transition")
    16.             {
    17.                 isIn = true;
    18.             }
    19.         }
    20.  
    21.         if (!isIn)
    22.         {
    23.             Assert.Fail("Fail: " + scene.name);
    24.         }
    25.     }
    26.  
    27.     Assert.Pass();
    28. }
     
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,291
    Here is something I wrote yesterday to do this.

    Code (CSharp):
    1. var assets = AssetDatabase.FindAssets ("t:Scene");
    2. for(int i = 0; i < assets.Length; ++i)
    3. {
    4.     var path = AssetDatabase.GUIDToAssetPath (assets[i]);
    5.     EditorSceneManager.OpenScene (path, OpenSceneMode.Single);
    6.  
    7.     // Do stuff
    8. }
    You should use EditorSceneManager for editor scripts as the other version is designed for runtime and defers some work to the next frame.
     
    Gearmoon likes this.
  3. robloz

    robloz

    Joined:
    Apr 27, 2013
    Posts:
    10
    Thanks it is working!!!!
     
    karl_jones likes this.