🖼

创建编辑器窗口

以一个具体案例详细说明扩展编辑器的步骤。该案例将会生成一个可以对 Prefab 进行各种操作的控制中心 Prefab Center 。

新建、关闭窗口

创建一个新的编辑器窗口会用到以下方法:

public static EditorWindow GetWindow(Type t, bool utility = false, string title = null, bool focus = true);
public static EditorWindow GetWindowWithRect(Type t, Rect rect, bool utility = false, string title = null);

上述两个方法作用基本相同,都是返回当前屏幕上的第一个类型为 t 的编辑器窗口,如果不存在则新建一个,前者以默认的方式创建窗口,后者则需要额外的参数 rect 指定窗口的位置。以下是对其他参数的简单解释:

t

编辑器窗口的类型,必须继承于 EditorWindow 类。

utility

生成窗口的类型,取 true 时生成浮动的实用程序窗口,否则生成普通的 Unity 标签页窗口

title

新建窗口的标题,如果为 null 则默认标题为类的名字。

focus

是否使该窗口成为焦点(如果存在该窗口)。新建的窗口一定会成为焦点。

新建脚本 Assets/Tools/PrefabCenter/Editor/PrefabCenter.cs 并加入代码:

using UnityEditor;

public class PrefabCenter : EditorWindow {
		[MenuItem("Tools/Prefab Center/Open #o")]
		static void OpenPrefabCenter() {
				EditorWindow window = GetWindow (typeof (PrefabCenter), false, "Prefab Center");
				window.Show ();
		}
}

关闭窗口则需要添加:

[MenuItem ("Tools/Prefab Center/Close #c", false)]
static void ClosePrefabCenter () {
		EditorWindow window = GetWindow (typeof (PrefabCenter), false, "Prefab Center");
		window.Close ();
}

[MenuItem ("Tools/Prefab Center/Close #c", true)]
static bool ClosePrefabCenterValidation () {
		return focusedWindow.GetType () == typeof (PrefabCenter);
}

当编辑器窗口拥有焦点时才可以关闭。

绘制编辑器窗口

一般的编辑器窗口都是通过重写 OnGUI 方法实现的。首先在窗口中绘制一个包含多个选项的工具栏,以表示 Prefab 所属于的种类。添加必须的变量和 OnGUI 重写:

int _toolBarIndex, _prevIndex;
private void OnGUI () {
		DrawToolBar ();
}
private void DrawToolBar () {
		GUIContent [] contents = {
				new GUIContent("All"),
				new GUIContent("Players"),
				new GUIContent("Enemies"),
				new GUIContent("Collectables"),
				new GUIContent("Blocks")
		};
		_prevIndex = _toolBarIndex;
		_toolBarIndex = GUI.Toolbar (new Rect (5, 5, position.width - 10, 17), _toolBarIndex, contents);
}

通定义 maxSizeminSize 可以设置窗口的最大、最小尺寸,把代码放在 Awake 方法中,从而在绘制窗口前确定这些基本数值 :

private void Awake () {
		minSize = new Vector2 (500, 200);
		maxSize = new Vector2 (800, maxSize.y);
}

此外,也可以在 Awake 方法中初始化一些所需的变量值。