開發者可以通過派生 EditorWindows 繪製完全自定義的窗口。
使用 EditorWindow.GetWindow()來打開窗口,在OnGUI中進行繪製。
通過實現 IHasCustomMenu 來添加菜單
可以在我們的窗口中繪製選中對象的預覽,就像 Inspector 的 Preview 子窗口
例子:
using UnityEngine;
using UnityEditor;
/// <summary>
/// 自定義窗口
/// </summary>
public class CustomEditorWindow : EditorWindow, IHasCustomMenu
{
[MenuItem("X/CustomWindow")]
static void ShowWindow()
{
CustomEditorWindow wnd = EditorWindow.GetWindow<CustomEditorWindow>();
wnd.Show();
}
/// <summary>
/// 擴展窗口右上角下拉菜單
/// </summary>
/// <param name="menu"></param>
void IHasCustomMenu.AddItemsToMenu(GenericMenu menu)
{
menu.AddDisabledItem(new GUIContent("Disabled"));
menu.AddItem(new GUIContent("Test1"), true, () => { Debug.Log("click Test1"); });
menu.AddItem(new GUIContent("Test2"), false, () => { Debug.Log("click Test2"); });
menu.AddSeparator("Test/");
menu.AddItem(new GUIContent("Test/Test3"), true, () => { Debug.Log("click Test3"); });
}
private Texture _Texture;
private float _FloatValue;
private Editor mEditor;
private GameObject go;
private void Awake()
{
Debug.Log("初始化調用");
_Texture = AssetDatabase.LoadAssetAtPath<Texture>("Assets/unity.png");
}
/// <summary>
/// 繪製窗口
/// </summary>
private void OnGUI()
{
GUILayout.Label("XXXXXX", EditorStyles.boldLabel);
_FloatValue = EditorGUILayout.Slider(_FloatValue, 0, 100);
if (_Texture != null)
GUI.DrawTexture(new Rect(0, 30, 100, 100), _Texture);
// 繪製 GameObject 的預覽
if(Selection.activeGameObject)
{
if (Selection.activeGameObject != go)
{
Editor.DestroyImmediate(mEditor);
mEditor = null;
}
if (mEditor == null)
mEditor = Editor.CreateEditor(Selection.activeGameObject);
mEditor.OnPreviewGUI(GUILayoutUtility.GetRect(500, 500), GUIStyle.none);
}
}
private void OnDestroy()
{
Debug.Log("銷燬時調用");
}
private void OnFocus()
{
Debug.Log("獲得焦點");
}
private void OnLostFocus()
{
Debug.Log("失去焦點");
}
private void OnInspectorUpdate()
{
//Debug.Log("Inspector 每幀更新");
}
private void OnHierarchyChange()
{
Debug.Log("Hierarchy 視圖改變時調用");
}
private void OnProjectChange()
{
Debug.Log("Project 視圖改變時調用");
}
private void OnSelectionChange()
{
Debug.Log("Project or Hierarchy 視圖選擇對象時調用");
}
private void Update()
{
//Debug.Log("每幀更新");
}
}