Extending the Editor
Unity允許你使用自己定制的inspectors和Editor Windows擴展編輯器,並且你可以使用定制的Property Drawers定義屬性集在inspector中如何展示,這一塊講述如何使用這些特性。
Editor Windows
你可以在你的app中創建任意數量的定制窗口。它們的表現就像Inspector,Scene或者其它內置的窗口。這是給你的游戲添加一個子系統用戶接口的絕佳方式。[比如地圖編輯器]
做一個自定義的Editor Window包含以下幾個簡單步驟:
1.創建腳本,繼承EditorWindow類
2.使用代碼去觸發窗口顯示自己
3.為你的工具實現GUI代碼
Derive From EditorWindow
為了制作你的Editor Window,你的腳本必須存放在一個叫做"Editor"的文件夾中。在這個腳本中創建一個類,它繼承自EditorWindow.然后在內部的OnGUI方法里面編寫你的GUI控制。
using UnityEngine; using UnityEditor; using System.Collections; public class Example:EditorWindow { void onGUI() { // The actual window code goes here } }
Showing the window
為了在屏幕上顯示窗口,制作一個menu item來顯示它,這個靠創建一個方法完成,而激活這個方法則是靠MenuItem屬性。
Unity的默認行為是循環利用窗口(即:再次選擇menu item會顯示已經存在的窗口。這是靠使用EditorWindow.GetWindow方法實現),例如:
using UnityEngine; using UnityEditor; using System.Collections; class MyWindow : EditorWindow { [MenuItem ("Window/My Window")] public static void ShowWindow () { EditorWindow.GetWindow(typeof(MyWindow)); } void OnGUI () { // The actual window code goes here } }
這會創造一個標准的,可停靠的編輯窗口,它會在指令之間保存它的位置,可以使用自定義的布局,等等。想要獲得更多的操控,你可以使用GetWindowWithRect.
Implementing Your Window's GUI
窗口中實際的內容靠實現OnGUI方法繪制。你在游戲內部GUI中使用的UnityGUI類(GUI和GUILayout)在這里也可以使用。此外我們提供了一些額外的GUI操作,它們在editor-only類里面:EditorGUI和EditorGUILayout。這些類添加在了普通類已經可用的控件集合里,所以你可以隨意的混合搭配使用它們。
下面的C#代碼展示了你如何添加GUI元素到自定義的EditorWindow中:
using UnityEditor; using UnityEngine; public class MyWindow : EditorWindow { string myString = "Hello World"; bool groupEnabled; bool myBool = true; float myFloat = 1.23f; // Add menu item named "My Window" to the Window menu [MenuItem("Window/My Window")] public static void ShowWindow() { //Show existing window instance. If one doesn't exist, make one. EditorWindow.GetWindow(typeof(MyWindow)); } void OnGUI() { GUILayout.Label ("Base Settings", EditorStyles.boldLabel); myString = EditorGUILayout.TextField ("Text Field", myString); groupEnabled = EditorGUILayout.BeginToggleGroup ("Optional Settings", groupEnabled); myBool = EditorGUILayout.Toggle ("Toggle", myBool); myFloat = EditorGUILayout.Slider ("Slider", myFloat, -3, 3); EditorGUILayout.EndToggleGroup (); } }
樣例代碼的執行結果如下圖:

還想獲得更多信息,可以看看在EditorWindow頁面的樣例和文檔
