[AddComponentMenu("Transform/AddComponentTest", 10)] public class AttributeTest : MonoBehaviour{}
[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..."); }
//在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!"); }
//三个参数分别控制菜单项的名称,是否激活,显示层级 [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; }
//第一个参数用来给定该特性的适用范围 [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)); } }
原文:https://www.cnblogs.com/tqw1215/p/13359776.html