Unity支持自行創(chuàng)建窗口,也支持自定義窗口布局。在Project視圖中創(chuàng)建一個(gè)Editor文件夾,在文件夾中在創(chuàng)建一條腳本。
自定義窗口需要讓腳本繼承EditorWindow在設(shè)置MenuItem,此時(shí)在Unity導(dǎo)航菜單欄中GameObjec->window就可創(chuàng)建一個(gè)自定義窗口。
EditorWindow.GetWindowWithRect() 和 EditorWindow.GetWindow()都可以創(chuàng)建一個(gè)窗口。前者可以規(guī)定窗口的區(qū)域,后者可通過鼠標(biāo)動(dòng)態(tài)的延伸窗口。參數(shù)1表示窗口的對(duì)象,參數(shù)2表示窗口的區(qū)域,參數(shù)3表示窗口類型true表示窗口不會(huì)被別的窗口覆蓋,參數(shù)4表示窗口的名稱。
using UnityEngine;
using UnityEditor;
public class MyEditor : EditorWindow
{
[MenuItem ("GameObject/window")]
static void AddWindow ()
{
//創(chuàng)建窗口
Rect wr = new Rect (0,0,500,500);
MyEditor window = (MyEditor)EditorWindow.GetWindowWithRect (typeof (MyEditor),wr,true,"widow name");
window.Show();
}
//輸入文字的內(nèi)容
private string text;
//選擇貼圖的對(duì)象
private Texture texture;
public void Awake ()
{
//在資源中讀取一張貼圖
texture = Resources.Load("1") as Texture;
}
//繪制窗口時(shí)調(diào)用
void OnGUI ()
{
//輸入框控件
text = EditorGUILayout.TextField("輸入文字:",text);
if(GUILayout.Button("打開通知",GUILayout.Width(200)))
{
//打開一個(gè)通知欄
this.ShowNotification(new GUIContent("This is a Notification"));
}
if(GUILayout.Button("關(guān)閉通知",GUILayout.Width(200)))
{
//關(guān)閉通知欄
this.RemoveNotification();
}
//文本框顯示鼠標(biāo)在窗口的位置
EditorGUILayout.LabelField ("鼠標(biāo)在窗口的位置", Event.current.mousePosition.ToString ());
//選擇貼圖
texture = EditorGUILayout.ObjectField("添加貼圖",texture,typeof(Texture),true) as Texture;
if(GUILayout.Button("關(guān)閉窗口",GUILayout.Width(200)))
{
//關(guān)閉窗口
this.Close();
}
}
//更新
void Update()
{
}
void OnFocus()
{
Debug.Log("當(dāng)窗口獲得焦點(diǎn)時(shí)調(diào)用一次");
}
void OnLostFocus()
{
Debug.Log("當(dāng)窗口丟失焦點(diǎn)時(shí)調(diào)用一次");
}
void OnHierarchyChange()
{
Debug.Log("當(dāng)Hierarchy視圖中的任何對(duì)象發(fā)生改變時(shí)調(diào)用一次");
}
void OnProjectChange()
{
Debug.Log("當(dāng)Project視圖中的資源發(fā)生改變時(shí)調(diào)用一次");
}
void OnInspectorUpdate()
{
//Debug.Log("窗口面板的更新");
//這里開啟窗口的重繪,不然窗口信息不會(huì)刷新
this.Repaint();
}
void OnSelectionChange()
{
//當(dāng)窗口出去開啟狀態(tài),并且在Hierarchy視圖中選擇某游戲?qū)ο髸r(shí)調(diào)用
foreach(Transform t in Selection.transforms)
{
//有可能是多選,這里開啟一個(gè)循環(huán)打印選中游戲?qū)ο蟮拿Q
Debug.Log("OnSelectionChange" + t.name);
}
}
void OnDestroy()
{
Debug.Log("當(dāng)窗口關(guān)閉時(shí)調(diào)用");
}
}