Search Unity

Get selected scenes (in hierarchy)

Discussion in 'Scripting' started by jvo3dc, Oct 14, 2019.

  1. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    How can you get the selected scenes in the hierarchy in the editor? (For a editor window that shows some information on the selected part in the hierarchy.)

    The object for a scene returned from Selection.objects is null. There is an ID returned from Selection.instanceIDs, but calling EditorUtility.InstanceIDToObject with this ID returns null again. Unlike other ID's this ID seems a negative number and it doesn't seem to relate to the ID of the scene asset as far as I can tell. For example:
    • Scene asset (UnityEngine.SceneAsset): 19108
    • Same scene in hierarchy (null): -1074
     
    Djayp and SugoiDev like this.
  2. TheDelhiDuck

    TheDelhiDuck

    Joined:
    Aug 29, 2014
    Posts:
    35
    Looks like instanceID maps directly to scene.handle, so to get the selected scene you could use:

    Code (CSharp):
    1.  
    2. public static Scene GetSelectedScene()
    3. {
    4.     for (int index = 0; index < SceneManager.sceneCount; index++)
    5.     {
    6.         var scene = SceneManager.GetSceneAt(index);
    7.         if (scene.handle == Selection.activeInstanceID)
    8.         {
    9.             return scene;
    10.         }
    11.     }
    12.     return default;
    13. }
    14.  
     
    SunnysideGames and joshcamas like this.