拓展编辑器(十八)_源生自定义菜单

  MenuItem是依托于Unity编辑器的菜单栏,换句话说就是无法设置它的位置。如果希望菜单的位置出现时更灵活的话,可以调用源生组定义菜单的方法。比如,可以在Scene视图中点击鼠标右键,此时会弹出一组源生自定义菜单。代码如下所示:

using UnityEngine;
using UnityEditor;

public class 源生自定义菜单 
{
    [InitializeOnLoadMethod]
    static void InitializeOnLoadMethod()
    {
        SceneView.onSceneGUIDelegate = delegate (SceneView sceneView)
        {
            Event e = Event.current;
            //鼠标右键抬起时
            if (e != null && e.button == 1 && e.type == EventType.MouseUp)
            {
                Vector2 mousePosition = e.mousePosition;
                //设置菜单项
                var options = new GUIContent[]
                {
                    new GUIContent("Test1"),
                    new GUIContent("Test2"),
                    new GUIContent(""),
                    new GUIContent("Test/Test3"),
                    new GUIContent("Test/Test4")
                };
                //设置菜单显示区域
                var selected = -1;
                var userData = Selection.activeGameObject;
                var width = 100;
                var height = 100;
                var position = new Rect(mousePosition.x, mousePosition.y - height,
                    width, height);
                //显示菜单
                EditorUtility.DisplayCustomMenu(position, options, selected,
                    delegate (object data, string[] opt, int select)
                    {
                        Debug.Log(opt[select]);
                    }, userData
                );
                e.Use();
            }
        };
    }
}

  在上述代码中,首先监听鼠标右键以及获取鼠标位置,接着使用EditorUtility.DisplayCustomMenu()方法弹出自定义菜单,以及监听菜单选择后的事件。

效果如下所示:

  

 

转载于:https://www.cnblogs.com/llllllvty/p/9932614.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值