擷取原理:unity 所有視窗界面都繼承自編輯器UnityEditor程式集下的EditorWindow。而所有的編輯器視窗都在UnityEditor程式集裡定義,是以,我們通過反射擷取UnityEditor程式集擷取所有視窗就可以了。
直接上代碼:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
class ZzgWindow : EditorWindow
{
static List<Type> windowList = new List<Type>();
[MenuItem("TestContextMenu/Open Window")]
static void Init()
{
var window = GetWindow(typeof(ZzgWindow));
window.titleContent = new GUIContent("ZZG");
window.position = new Rect(200, 200, 400, 800);
window.Show();
windowList = getWindowAll();
}
[MenuItem("TestContextMenu/getWindowAll")]
static void getWindow()
{
windowList = getWindowAll();
}
/// <summary>
/// 擷取所有視窗類型
/// </summary>
/// <returns></returns>
static List<Type> getWindowAll()
{
Assembly assembly = typeof(EditorWindow).Assembly; //擷取UnityEditor程式集,當然你也可以直接加載UnityEditor程式集來擷取,我這裡圖友善,具體方法看一下程式集的加載Assembly.Load();
Type[] types = assembly.GetTypes();
List<Type> list =new List<Type>();
for (int i = 0; i < types.Length; i++)
{
if (isEditorWindow(types[i]))
{
if (types[i].Name == "GameView")
{
Debug.Log(types[i].FullName);
}
if (types[i].Name == "SceneView")
{
Debug.Log(types[i].FullName);
}
list.Add(types[i]);
}
}
list.Sort((a,b)=> { return string.Compare(a.Name, b.Name); }); //排序
return list;
}
/// <summary>
/// 判斷是否是編輯器視窗
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
static bool isEditorWindow(Type type)
{
int i = 0;
Type temp = type;
while (null !=temp&&i<10000)
{
i++;
if (temp.BaseType == typeof(EditorWindow))
{
return true;
}
temp = temp.BaseType;
}
return false;
}
/// <summary>
/// 關閉所有視窗
/// </summary>
void closeWindowAll()
{
for (int i = 0; i < windowList.Count; i++)
{
try
{
EditorWindow editorWindow = EditorWindow.GetWindow(windowList[i]);
if (editorWindow)
{
editorWindow.Close(); //關閉視窗
}
}
catch
{
}
}
}
void showWindowAll()
{
for (int i = 0; i < windowList.Count; i++)
{
try
{
EditorWindow editorWindow = EditorWindow.GetWindow(windowList[i]);
if (editorWindow)
{
editorWindow.Show(); //打開視窗
}
}
catch
{
}
}
}
/// <summary>
/// 顯示指定類型視窗
/// </summary>
/// <param name="type"></param>
void showWindow(Type type)
{
try
{
EditorWindow editorWindow = EditorWindow.GetWindow(type);
if (editorWindow)
{
editorWindow.Show();
}
}
catch
{
}
}
Vector2 pos = new Vector2(0,0);
void OnGUI()
{
if (GUILayout.Button("關閉所有視窗"))
{
closeWindowAll();
}
//if (GUILayout.Button("打開所有視窗"))
//{
// showWindowAll();
//}
pos = GUILayout.BeginScrollView(pos);
for (int i = 0; i < windowList.Count; i++)
{
if (GUILayout.Button(windowList[i].Name))
{
showWindow(windowList[i]);
}
}
GUILayout.EndScrollView();
}
}
代碼有注釋,不再解釋了。editorWindow.Close()關閉視窗。editorWindow.Show()顯示視窗
首先關閉所有視窗如下圖:界面真幹淨

然後我們通過點選上面的按鈕打開unity自帶的視窗: