首页 > 编程语言 > 详细

Unity3D自定义菜单组件

时间:2020-07-22 14:36:37      阅读:72      评论:0      收藏:0      [点我收藏+]
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));
    }
}

Unity3D自定义菜单组件

原文:https://www.cnblogs.com/tqw1215/p/13359776.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!