NGUI中的MenuItem
什么是MenuItem
MenuItem是静态函数的注解,它能将静态函数转化为menu command。它允许你向主菜单添加菜单选项,Project右键菜单添加以及向Inspector属性面板添加context menu上下文菜单选项。
Menu在计算机领域的意思是一系列的指令或者选项。(a list of commands or options, especially one displayed on screen.)
[MenuItem("NGUI/Options/Handles/Set to Blue", false, 10)]
static public void SetToBlue () { NGUISettings.colorMode = NGUISettings.ColorMode.Blue; }
[MenuItem("CONTEXT/UIWidget/Log Widget")]
static void LogWidget (MenuCommand command)
{
var widget = command.context as UIWidget;
Debug.Log(widget);
}
[MenuItem("Assets/NGUI/Log a message", false, 1)]
static void AssetMenuLog() { Debug.Log("log a message"); }



MenuItem类的构造函数
MenuItem可以通过修改构造函数中的参数来设置 validate 函数,用于disable对应的MenuItem。
//
// Summary:
// Creates a menu item and invokes the static function that follows it when the
// menu item is selected.
//
// Parameters:
// itemName:
// The itemName is the menu item represented like a pathname. For example, the menu
// item could be "GameObject/Do Something".
//
// isValidateFunction:
// If isValidateFunction is true, this is a validation function and is called before
// the menu function with the same itemName is invoked.
//
// priority:
// The order by which the menu items are displayed.
public MenuItem(string itemName, bool isValidateFunction, int priority)
: this(itemName, isValidateFunction, priority, internalMenu: false)
{
}
MenuItem的快捷键
To create a hotkey, use the following special characters: % (ctrl on Windows and Linux, cmd on macOS), ^ (ctrl on Windows, Linux, and macOS), # (shift), & (alt). If no special modifier key combinations are required, the key can be given after an underscore. For example, to create a menu with the hotkey Shift+Alt+G, use "MyMenu/Do Something #&g". To create a menu with hotkey G and no key modifiers pressed, use "MyMenu/Do Something _g". Hotkey text must be preceded by a space character. <tt>"MyMenu/Do_g"</tt> won't be interpreted as hotkey, while <tt>"MyMenu/Do _g"</tt> will.
Some special keyboard keys are supported as hotkeys. For example, "#LEFT" would map to Shift-Left. The keys supported like this are: LEFT, RIGHT, UP, DOWN, F1 .. F12, HOME, END, PGUP, PGDN, INS, DEL, TAB, and SPACE.
向GameObject目录添加MenuItem
When adding menu items to the "GameObject/" menu to create custom GameObjects, be sure to call GameObjectUtility.SetParentAndAlign to ensure that the new GameObject is reparented correctly in the case of a context click (see example below). Your function should also call Undo.RegisterCreatedObjectUndo to make the creation undoable and set Selection.activeObject to the newly created object. Also note that in order for a menu item in "GameObject/" to be propagated to the hierarchy Create dropdown and hierarchy context menu, it must be grouped with the other GameObject creation menu items. This can be achieved by setting its priority to 10 (see example below). Note that for legacy purposes MenuItems in "GameObject/Create Other" with no explicit priority set will receive a priority of 10 instead of the default 1000 - we encourage using a more descriptive category name than "Create Other" and explicitly setting the priority to 10.
MenuItem官方案例代码
using UnityEditor;
using UnityEngine;
public class MenuTest : MonoBehaviour
{
// Add a menu item named "Do Something" to MyMenu in the menu bar.
[MenuItem("MyMenu/Do Something")]
static void DoSomething()
{
Debug.Log("Doing Something...");
}
// Add a menu item named "Log Selected Transform Name" to MyMenu in the menu bar.
// We want this to be validated menu item: an item that is only enabled if specific conditions are met.
// To achieve this, we use a second function below to validate the menu item.
// so it will only be enabled if we have a transform selected.
[MenuItem("MyMenu/Log Selected Transform Name")]
static void LogSelectedTransformName()
{
Debug.Log("Selected Transform is on " + Selection.activeTransform.gameObject.name + ".");
}
// Validate the menu item defined by the function above.
// The "Log Selected Transform Name" menu item is disabled if this function returns false.
// We tell the Editor that this is a validation function by decorating it with a MenuItem attribute
// and passing true as the second parameter.
// This invokes the MenuItem(string itemName, bool isValidateFunction) attribute constructor
// resulting in the function being treated as the validator for "Log Selected Transform Name" menu item.
[MenuItem("MyMenu/Log Selected Transform Name", true)]
static bool ValidateLogSelectedTransformName()
{
// Return false if no transform is selected.
return Selection.activeTransform != null;
}
// Add a menu item named "Do Something with a Shortcut Key" to MyMenu in the menu bar
// and give it a shortcut (ctrl-g on Windows, cmd-g on macOS).
[MenuItem("MyMenu/Do Something with a Shortcut Key %g")]
static void DoSomethingWithAShortcutKey()
{
Debug.Log("Doing something with a Shortcut Key...");
}
// Add a menu item called "Double Mass" to a Rigidbody's context menu.
[MenuItem("CONTEXT/Rigidbody/Double Mass")]
static void DoubleMass(MenuCommand command)
{
Rigidbody body = (Rigidbody)command.context;
body.mass = body.mass * 2;
Debug.Log("Doubled Rigidbody's Mass to " + body.mass + " from Context Menu.");
}
// Add a menu item to create custom GameObjects.
// Priority 10 ensures it is grouped with the other menu items of the same kind
// and propagated to the hierarchy dropdown and hierarchy context menus.
[MenuItem("GameObject/MyCategory/Custom Game Object", false, 10)]
static void CreateCustomGameObject(MenuCommand menuCommand)
{
// Create a custom game object
GameObject go = new GameObject("Custom Game Object");
// Ensure it gets reparented if this was a context click (otherwise does nothing)
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject);
// Register the creation in the undo system
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
Selection.activeObject = go;
}
}
NGUI中的MenuItem
NGUI主菜单的Menu Command
都在NGUIMenu.cs
中,少部分GameObject相关的指令还位于NGUISelectionTools.cs。
NGUI中的GenericItem
NGUI Inspector的Menu以及在scene view中点击产生的命令菜单的代码位于NGUIContextMenu.cs
中。
使用Context MenuItem 打开脚本的CustomEditor
项目开发中,我们经常需要自己编写脚本的Inspector代码,而Editor类和脚本位于两个Project,寻找对应的CustomEditor经常会花费一定的时间。
这里我们可以通过添加Context MenuItem来实现直接跳转到对应的CustomEditor
[MenuItem("CONTEXT/UIRect/Edit Script (Editor)")]
private static void OpenEditorScript(MenuCommand command)
{
var uiRect = command.context as UIRect;
var editor = Editor.CreateEditor(uiRect);
var editorFileName = $"{editor.GetType()}";
var guid = AssetDatabase.FindAssets(editorFileName).First();
var assetPath = AssetDatabase.GUIDToAssetPath(guid);
var assetObj = AssetDatabase.LoadAssetAtPath(assetPath, typeof(UnityEngine.Object));
AssetDatabase.OpenAsset(assetObj);
Editor.DestroyImmediate(editor);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!