Version: 2022.3

MenuItemConstructor

切换到手册
public MenuItem (string itemName);
public MenuItem (string itemName, bool isValidateFunction);
public MenuItem (string itemName, bool isValidateFunction, int priority);

参数

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 菜单项显示的顺序。

描述

Creates a menu item and invokes the static function that follows it when the menu item is selected.

MenuItem is an attribute that precedes a script function. This makes the function appear in the Unity menu system. The menu location is specified by the itemName argument.

isValidateFunction is used to make a MenuItem function as one is executed before a script function with the same itemName argument. The second argument is boolean. If this argument is set to true, it marks the associated function to be called before the execution of the second script function. This second script function with the same itemName executes next.

priority determines how the following script function is ordered in the menu system. The integer value is compared against values on other script functions. Parent menus derive their priority value from their first defined submenu. If the integer value is greater than the other values, then the MenuItem script function is placed at the bottom of the list. The value of priority can also be used to manage the list of script functions into groups. The example later in this page demonstrates more about this feature.

The following script example adds two functions into an Example menu system.

using UnityEngine;
using UnityEditor;
using System.Collections;

public class ExampleClass : MonoBehaviour { // Add Example1 into a new menu list [MenuItem("Example/Example1", false, 100)] public static void Example1() { print("Example/Example1"); }

// Add Example2 into the same menu list [MenuItem("Example/Example2", false, 100)] public static void Example2() { print("Example/Example2"); } }

The following example shows how the Example menu can have two entries divided by a separator line. When a priority argument is separated by more than 10, a separator line is created between two entries.

using UnityEngine;
using UnityEditor;
using System.Collections;

public class ExampleClass : MonoBehaviour { // Add Example1 has priority of 100 [MenuItem("Example/Example1", false, 100)] public static void Example1() { print("Example/Example1"); }

// Example2 has a priority of 111 which is 11 more than Example1. // This will cause a divider to be created. [MenuItem("Example/Example2", false, 111)] public static void Example2() { print("Example/Example2"); } }

**注意:**10 或更大值会被理解成能够在菜单中 创建一个分隔栏。然而,根据上面的示例来看,脚本函数 之间的差异需要使 priority 之间所间隔的级别为 11 或更大值。这就是 为什么在上面的示例中一个值为 100 而另一个值 111。将 111 更改为 110 将 不会产生分隔栏。