1.在Component菜单栏中添加新的菜单项
[AddComponentMenu("Transform/AddComponentTest", 10)] public class AttributeTest : MonoBehaviour{}
点击AddComponentTest则可以向目标GameObject添加AttributeTest脚本

2.添加新的菜单栏以及菜单项
[MenuItem("MyMenu/Do Something")]//MenuItem特性会将所有的静态方法变为菜单命令 static void DoSomething() { } //定义一个输出Transform名称的选项,首先要判断选中的是不是Transform对象,不是则不激活该选项 [MenuItem ("MyMenu/Log Selected Transform Name")] static void LogSelectedTransformName() { Debug.Log(Selection.activeTransform.gameObject.name); } //判断是否激活菜单项,返回true则激活 [MenuItem ("MyMenu/Log Selected Transform Name", true)] static bool IsActiveMenu() { return Selection.activeTransform != null; } //创建菜单项并添加快捷键Ctrl + G [MenuItem ("MyMenu/Do Something With A Shortcut Key %g")] static void DoSomethingWithAShortcutKey() { Debug.Log("Do Something With A Shortcut Key..."); }
3.在Component组件的Context中添加新的菜单项
//在Unity中Rigidbody的context增加一个Double Mass菜单项 [MenuItem ("CONTEXT/Rigidbody/Double Mass")] static void DoubleMass(MenuCommand command) { Rigidbody body = (Rigidbody)command.context; body.mass = body.mass * 2; Debug.Log("Change Mass Double!"); }
4.创建一个新的自定义GameObject
//三个参数分别控制菜单项的名称,是否激活,显示层级 [MenuItem("GameObject/MyCaregory/Custom Game Object", false, 10)] static void CreateCustomGameObject(MenuCommand command) { GameObject go = new GameObject("Custom Game Object"); GameObjectUtility.SetParentAndAlign(go, command.context as GameObject); Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); Selection.activeObject = go; }
5.定义自己的定制特性类
//第一个参数用来给定该特性的适用范围 [AttributeUsage(AttributeTargets.Class, Inherited = false)] public class CustomAttribute : System.Attribute{ } [CustomAttribute] public class CustomAttributeTest : MonoBehaviour { void Start() { //打印为True Debug.Log(this.GetType().IsDefined(typeof(CustomAttribute), false)); } }