unity是一个强大的编辑器。 我们可以通过一些代码扩展它,达到提高工作效率的目的。
在开始写代码之前, 我们需要先知道一些前置知识。
- 命名空间。Unity的运行时和编辑器类分别存储在不同的Assemblies里:UnityEngine 和 UnityEditor。编写编辑器之前,需要
using UnityEditor
。 - 当想在编辑器中执行脚本时, 可以使用 attribute:[ExecuteInEditMode]通知编辑器, 被描述类的 OnGUI 和 Update 等函数在编辑模式也会被调用。
- 当代码在运行时和编辑器都需要执行时,可以使用 #if UNITY_EDITOR … #endif 宏来对编辑器代码做特殊处理。
本文主要介绍了以下几个方法:
- MenuItem
- AddComponentMenu
- ContextMenu
- ScriptableObject
- EditorWindow
- Editor
- ScriptableWizard
其中 MenuItem, AddComponentMenu, ContextMenu 并不会用到 UnityEditor 命名空间。
ScriptableObject, EditorWindow, Editor, ScriptableWizard 需要使用 UnityEditor 命名空间。
MenuItem:在菜单栏加item
[MenuItem(“dir/name”)]:MenuItem属性允许您将菜单项添加到主菜单和 inspector context 菜单。
https://docs.unity3d.com/ScriptReference/MenuItem.html
- MenuItem必须定义子菜单, 如[MenuItem(“dir”)] 是不行的。
- MenuItem 属性必须写在一个静态方法之前;
using UnityEditor;
using UnityEngine;
public class t_MenuItem : MonoBehaviour {
[MenuItem("MyMenu/Do Something")]
static void DoSomething() {
Debug.Log("Doing Something...");
}
[MenuItem("MyMenu/Log Selected Transform Name")]
static void LogSelectedTransformName() {
Debug.Log("Selected Transform is on " + Selection.activeTransform.gameObject.name + ".");
}
[MenuItem("MyMenu/Log Selected Transform Name", true)]
static bool ValidateLogSelectedTransformName() {
return Selection.activeTransform != null;
}
[MenuItem("MyMenu/Do Something with a Shortcut Key %g")]
static void DoSomethingWithAShortcutKey() {
Debug.Log("Doing something with a Shortcut Key...");
}
}