Home Unity Eitor扩展 -- MenuItem
Post
Cancel

Unity Eitor扩展 -- MenuItem

MenuItem是在UnityEditor命名空间下的一个类,它允许你可以在Unity编辑器中添加自定义的菜单,同时也可以允许添加快捷键。

基本的菜单设置

MenuItem只适用于静态static方法,这个属性可以让静态方法转变为菜单指令。下图代码可以让Dosomething方法添加到MyMenu/Do something菜单当中。

1
2
3
4
5
[MenuItem("MyMenu/Do Something")]
static void DoSomething()
{
    Debug.Log("Doing Something...");
}

添加菜单快捷键

如果想让这个方法通过快捷键来进行调用,则可以在字段最后空一格,输入相应的快捷键操作,例如将这个方法的快捷键设置成ctrl+shift+q,如下图代码所示

必须要空一格才能识别快捷键

1
2
3
4
5
[MenuItem("MyMenu/Do Something %#q")]
static void DoSomething()
{
    Debug.Log("Doing Something...");
}

以下是不同快捷键所对应的字符:

  • % (ctrl on Windows and Linux, cmd on macOS)
  • ^ (ctrl on Windows, Linux, and macOS)
  • # (shift)
  • & (alt)

添加Comoponent菜单快捷键

除了在Editor的编辑器的菜单栏上添加,还可以在组件的菜单栏上面进行添加,如图上代码所示,代码里演示了如何将一个static方法添加的组件菜单当中。

1
2
3
4
5
6
7
[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.");
}

UnityRigidbody示意图

除此之外,MenuItem其实一共有三个参数

  • ItemName 设置菜单的位置以及快捷键的设置
  • isValidateFunction 当设置为true时,函数将会在具有相同ItemName的方法前调用
  • priority 优先级的设置,越小优先级级越高

以下是一个具体的例子,来解释了第二个参数isValidateFunction的用法

1
2
3
4
5
6
7
8
9
10
11
    [MenuItem("Example/Example1", true)]
    public static bool Example2()
    {
        return Selection.activeGameObject != null;
    }
    
    [MenuItem("Example/Example1", false)]
    public static void Example1()
    {
        Debug.Log(Selection.activeGameObject.name);
    }

这是第二个参数的常用用法,通过判断是否选择了一个GameObject来判断这个菜单栏是否可以被点击,return为true时可以被点击,为false时不可以被点击。

其中Example2函数中的代码会在两个地方进行回调,一个是关闭菜单栏的时候,一个是点击菜单栏的时候。

第三个参数priority非常好理解,在相同路径的菜单栏下,priority越小,其位置越靠上。

注意:当两个菜单之间的priority相差10以上的时候,彼此之间会自动产生分隔行

This post is licensed under CC BY 4.0 by the author.