自定义绘制窗口并监听
using UnityEditor;
using UnityEngine;
namespace Scripts_03.Editor
{
#region EditorWindows窗口
public class ExpandWindow : EditorWindow, IHasCustomMenu
{
public void AddItemsToMenu(GenericMenu menu)
{
// 禁用菜单
menu.AddDisabledItem(new GUIContent("禁用菜单"));
menu.AddItem(new GUIContent("菜单1"), true, () =>
{
Debug.Log("菜单1");
});
menu.AddSeparator(""); // 分割线
menu.AddItem(new GUIContent("菜单2/菜单2-1"), false, () =>
{
Debug.Log("菜单2/菜单2-1");
});
}
[MenuItem("Window/Open My Window")]
static void Init()
{
ExpandWindow window = GetWindow<ExpandWindow>(typeof(ExpandWindow));
window.Show();
}
private Texture _texture;
private float _slider = 0.5f;
void Awake()
{
Debug.Log("Awake ----> 窗口初始化时调用");
_texture = AssetDatabase.LoadAssetAtPath<Texture>("Assets/unity.png");
}
void OnGUI()
{
// Debug.Log("绘制窗口");
GUILayout.Label("Hello World!!", EditorStyles.boldLabel);
var guiStyle = new GUIStyle();
guiStyle.fixedWidth = 100;
guiStyle.fixedHeight = 100;
GUILayout.Box(_texture, guiStyle);
_slider = EditorGUILayout.Slider("Slider", _slider, -10, 10);
}
void OnFocus()
{
Debug.Log("OnFocus ----> 拥有焦点");
}
void OnLostFocus()
{
Debug.Log("OnLostFocus ----> 失去焦点");
}
void OnSelectionChange()
{
Debug.Log("OnSelectionChange ----> 在 Hierarchy 或者 Project 视图中选择一个对象时调用");
}
void OnHierarchyChange()
{
Debug.Log("OnHierarchyChange ----> Hierarchy 视图发生改变时调用");
}
void OnProjectChange()
{
Debug.Log("OnProjectChange ----> Project 视图发生改变时调用");
}
void Update()
{
// Debug.Log("Update ----> 每帧更新");
}
void OnInspectorUpdate()
{
// Debug.Log("OnInspectorUpdate ----> Inspector 每帧更新");
}
void OnDestroy()
{
Debug.Log("OnDestroy ----> 窗口销毁时调用");
}
}
#endregion
}
自定义GameObject预览窗口示例
using UnityEditor;
using UnityEngine;
public class GameObjPreview : EditorWindow
{
private GameObject _gameObject;
private Editor _editor;
[MenuItem("Window/GameObject预览")]
public static void ObjPreview()
{
GameObjPreview window = GetWindow<GameObjPreview>(typeof(GameObjPreview));
window.Show();
}
private void OnGUI()
{
GUILayout.Label("Hello GameObject!!!");
var gameObject = (GameObject)EditorGUILayout.ObjectField(_gameObject, typeof(GameObject), true);
// 每次gameObject改变时都实例化_editor(gameObject != _gameObject ---> 比较当前GameObject与上一次的区别)
if (gameObject != _gameObject)
{
_gameObject = gameObject;
_editor = Editor.CreateEditor(_gameObject);
}
if (_gameObject != null)
_editor.OnPreviewGUI(GUILayoutUtility.GetRect(300, 300), EditorStyles.whiteLabel);
}
}