73 lines
2.6 KiB
C#
73 lines
2.6 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using UnityEditor;
|
||
using UnityEngine;
|
||
|
||
namespace Aliciza.UXTool
|
||
{
|
||
public static partial class ContextMenuUtils
|
||
{
|
||
private static GenericMenu contextMenu = new GenericMenu(); // 保存当前菜单
|
||
private static HashSet<string> menuItems = new HashSet<string>(); // 用于跟踪菜单项,防止重复
|
||
private static bool menuBuilt = false; // 标记是否已构建菜单
|
||
|
||
// 清空现有菜单和菜单项,重新构建菜单
|
||
static void ResetMenu()
|
||
{
|
||
contextMenu = new GenericMenu();
|
||
menuItems.Clear();
|
||
menuBuilt = false;
|
||
}
|
||
|
||
// 判断菜单是否为空
|
||
public static bool IsMenuEmpty()
|
||
{
|
||
// 判断contextMenu是否有任何项,若没有,则菜单为空
|
||
return contextMenu.GetItemCount() == 0; // 如果没有菜单项,返回 true
|
||
}
|
||
|
||
// 显示菜单
|
||
public static void ShowContextMenu()
|
||
{
|
||
if (!menuBuilt) BuildContextMenu(); // 如果菜单尚未构建,则构建菜单
|
||
if (!IsMenuEmpty()) // 如果菜单项不为空,则显示菜单
|
||
{
|
||
contextMenu.ShowAsContext();
|
||
}
|
||
ResetMenu(); // 显示完菜单后重置
|
||
}
|
||
|
||
// 构建普通菜单项
|
||
public static void BuildContextMenu(string label, bool check, GenericMenu.MenuFunction clickEvent)
|
||
{
|
||
if (menuItems.Contains(label)) return; // 防止重复添加相同的菜单项
|
||
contextMenu.AddItem(new GUIContent(label), check, clickEvent);
|
||
menuItems.Add(label);
|
||
menuBuilt = true;
|
||
}
|
||
|
||
// 构建带参数的菜单项
|
||
public static void BuildContextMenuWithArgs(string label, bool check, GenericMenu.MenuFunction2 clickEvent, object arg1)
|
||
{
|
||
if (menuItems.Contains(label)) return; // 防止重复添加相同的菜单项
|
||
contextMenu.AddItem(new GUIContent(label), check, clickEvent, arg1);
|
||
menuItems.Add(label);
|
||
menuBuilt = true;
|
||
}
|
||
|
||
// 添加分隔符
|
||
public static void BuildSeparator()
|
||
{
|
||
contextMenu.AddSeparator(string.Empty); // 添加一个通用的分隔符
|
||
menuBuilt = true;
|
||
}
|
||
|
||
// 为了确保每次显示菜单之前都进行初始化
|
||
static void BuildContextMenu()
|
||
{
|
||
// 在这里可以添加额外的默认菜单项(如果有需要的话)
|
||
menuBuilt = true; // 表示菜单已经构建
|
||
}
|
||
}
|
||
}
|