菜单快捷键、菜单选中、菜单禁用
效果
源码
using UnityEditor;
using UnityEngine;
public class ExpandMenu
{
#region
// 禁用菜单
[MenuItem("Root/Menu/Button")]
private static void MenuButton()
{
Debug.Log($"{Selection.activeObject}");
}
// 禁用菜单 (参数2为true时表明这是一个验证函数,当返回值为true时,该菜单项才可以进行选择,否则不可选择)
[MenuItem("Root/Menu/Button", true, 0)]
private static bool MenuButtonDisabled()
{
return Selection.activeObject != null;
}
#endregion
// 可选菜单
[MenuItem("Root/Menu/Checkbox", false, 11)]
private static void MenuCheckbox()
{
var menuPath = "Root/Menu/Checkbox";
bool isChecked = Menu.GetChecked(menuPath);
Menu.SetChecked(menuPath, !isChecked);
Debug.Log($"可选菜单 ---> {!isChecked}");
}
// 拓展全局自定义快捷键
[MenuItem("Root/HotKey %#d", false, -1)]
private static void HotKey()
{
var message = "";
message += "【1】 %:表示 Windows 下的 Ctrl 键和 macOS 下的 Command 键。\n\n";
message += "【2】 #:表示 Shift 键。\n\n";
message += "【3】 &:表示 Alt 键。\n\n";
message += "【4】 LEFT/RIGHT/UP/DOWN:表示左、右、上、下 4 个方向键。\n\n";
message += "【5】 F1…F12:表示 F1 至 F12 菜单键。\n\n";
message += "【6】 HOME、END、PGUP 和 PGDN 键。";
EditorUtility.DisplayDialog("快捷键", message, "Ok");
}
}
源生自定义菜单
效果
源码
// 源生自定义菜单
[InitializeOnLoadMethod]
static void InitializeOnLoadMethod()
{
SceneView.duringSceneGui += delegate
{
// 鼠标事件
Event e = Event.current;
// 鼠标右键抬起时
if (e is { button: 1, type: EventType.MouseUp })
{
// 获取鼠标点击位置
Vector2 mousePosition = e.mousePosition;
// 设置菜单项
GUIContent[] menus =
{
new GUIContent("菜单 1"),
new GUIContent("菜单 2"),
new GUIContent(""), // 分割线
new GUIContent("菜单 3/菜单 3-1"),
new GUIContent("菜单 3/菜单 3-2"),
};
// 绘制菜单
const int width = 100;
const int height = 100;
Rect position = new Rect(mousePosition.x, mousePosition.y - height, width, height);
const int selected = -1; // 默认选中的菜单 -1不选中; 0选中菜单1; 1选中菜单2; 2不选中; 3选中菜单3-1; 4选中菜单3-2
object userData = Selection.activeObject;
EditorUtility.DisplayCustomMenu(position, menus, selected, (data, options, i) =>
{
// 选中的回调函数 弹框 data根据参数userData判断为选中的游戏对象
EditorUtility.DisplayDialog(options[i], data?.ToString(), "Ok");
}, userData);
e.Use(); // 不再执行原有的操作
}
};
}