Unity编辑器扩展 - 菜单项
发表于2018-04-22
Unity编辑器允许添加外观和行为与内置菜单相似的自定义菜单。这对于添加常用的功能非常有用,这些功能通常需要通过编辑器UI直接访问。本篇文章将和大家介绍如何创建Unity编辑器中的新菜单项。


添加菜单项
为了将新菜单添加到顶层工具栏,您应该创建一个编辑器脚本(一个脚本文件,该文件位于项目中名为Editor的文件夹下的任何位置)。菜单项在脚本代码中被创建为静态方法,用MenuItem属性标记。
例如,通常添加一个新的“工具”菜单(或带有公司名称的顶级菜单)以提供您的团队/公司常用的选项。
以下是添加新工具菜单并在其下面添加一个选项(清除所有PlayerPrefs数据)的示例:
using UnityEngine; using UnityEditor; public class MenuItems { [MenuItem("Tools/Clear PlayerPrefs")] private static void NewMenuOption() { PlayerPrefs.DeleteAll(); } }
来扩展已有/自定义菜单按钮,上述代码中的Tools可替换为Window这样的原有菜单项。
热键
为了方便大家工作,可以使用热键分配新菜单项 - 快捷键组合将自动启动它们。
- % – CTRL on Windows / CMD on OSX
- # – Shift
- & – Alt
- LEFT/RIGHT/UP/DOWN – Arrow keys
- F1…F2 – F keys
- HOME, END, PGUP, PGDN
// Add a new menu item with hotkey CTRL-SHIFT-A [MenuItem("Tools/New Option %#a")] private static void NewMenuOption() { } // Add a new menu item with hotkey CTRL-G [MenuItem("Tools/Item %g")] private static void NewNestedOption() { } // Add a new menu item with hotkey G [MenuItem("Tools/Item2 _g")] private static void NewOptionWithHotkey() { }
特殊路径
上面文章中讲到的按钮路径都是普通的位于菜单栏的按钮,但是Untiy是有一些特殊的路径的,比如:
- Assets – items will be available under the “Assets” menu, as well using right-click inside the project view.(我们在Unity的Project下面右击会出现的)
- Assets/Create – items will be listed when clicking on the “Create” button in the project view (useful when adding new types that can be added to the project)(Unity的Project目录下右击->Create下面)
- CONTEXT/ComponentName – items will be available by right-clicking inside the inspector of the given component.(在面板上的组件上右击会出现)
Validation/验证?
有些按钮只有在右击某类东西时才会起作用,所以我们需要验证,例子如下:
[MenuItem("Assets/ProcessTexture")] private static void DoSomethingWithTexture() { } // Note that we pass the same path, and also pass "true" to the second argument. [MenuItem("Assets/ProcessTexture", true)] private static bool NewMenuOptionValidation() { // This returns true when the selected object is a Texture2D (the menu item will be disabled otherwise). return Selection.activeObject.GetType() == typeof(Texture2D); }
效果:只有在Texture2D上才会有用

按钮优先级
[MenuItem("NewMenu/Option1", false, 1)] private static void NewMenuOption() { } [MenuItem("NewMenu/Option2", false, 2)] private static void NewMenuOption2() { } [MenuItem("NewMenu/Option3", false, 3)] private static void NewMenuOption3() { } [MenuItem("NewMenu/Option4", false, 51)] private static void NewMenuOption4() { } [MenuItem("NewMenu/Option5", false, 52)] private static void NewMenuOption5() { }
效果:以10为单位一组

End.除此之外还有MenuCommand、ContextMenu、ContextMenuItem等几个类,跟MenuItem差不多。
参考资料:https://unity3d.com/cn/learn/tutorials/topics/interface-essentials/unity-editor-extensions-menu-items?playlist=17090
来自:https://blog.csdn.net/rickshaozhiheng/article/details/50598143