Home > Software design >  How to create a window in Unity from a script and attach it to an existing tab?
How to create a window in Unity from a script and attach it to an existing tab?

Time:03-03

i'm trying to make a custom editor script for Unity, but i'm stuck in what I thought would be an easy step. When using UnityEditor.GetWindow(), the window doesn't open in the main tab but as a separate Window. enter image description here


Now if you actually want to have it docked no matter what tab is opened you could use reflection to find just each and every inheritor of EditorWindow and do

using Linq;

...

var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()).Where(type =>type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(EditorWindow))).ToArray();
// This kind of equals doing something like
//var typesList = new List<Type>();
//var assemblies = AppDomain.CurrentDomain.GetAssemblies();
//foreach(var assembly in assemblies)
//{
//    var allTypes = assembly.GetTypes();
//    foreach(var type in allTypes)
//    {
//        if(type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(EditorWindow)))
//        {
//            typesList.Add(type);
//        }
//    }
//}
//var types = typesList.ToArray();

var window = GetWindow<YOURWINDOW>(types);

Note though that due to order the ConsoleWindow is kinda the first entry almost so if there is a console tab opened it would always first attach to that one ^^

You can still add your preferred ones though like e.g.

var types = new List<Type>()
{ 
    // first add your preferences
    typeof(SceneView), 
    typeof(Editor).Assembly.GetType("UnityEditor.GameView"),
    typeof(Editor).Assembly.GetType("UnityEditor.SceneHierarchyWindow"),
    typeof(Editor).Assembly.GetType("UnityEditor.ConsoleWindow"), 
    typeof(Editor).Assembly.GetType("UnityEditor.ProjectBrowser"), 
    typeof(Editor).Assembly.GetType("UnityEditor.InspectorWindow")
};

// and then add all others as fallback (who cares about duplicates at this point ? ;) )
types.AddRange(AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()).Where(type =>type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(EditorWindow))));
var window = GetWindow<YOURWINDOW>(types.ToArray());
 

since it literally goes through this array from start to end and uses the first matching opened window type.

  • Related