zoukankan      html  css  js  c++  java
  • Unity编辑器

    Unity编辑器 - DragAndDrop拖拽控件

    Unity编辑器的拖拽(DragAndDrop)在网上能找到的资料少,自己稍微研究了一下,写了个相对完整的案例,效果如下

    拖拽控件

    代码:

    object dragData = "dragData";
    Vector2 offset;
    Color col = new Color(1, 0, 0, 0.6f);
    Rect rect1 = new Rect(20, 10, 100, 20);
    Rect rect2 = new Rect(20, 60, 100, 20);
    Rect drect;
    bool isDraging;
    int cid;
    
    private void OnGUI() {
        GUI.Box(rect1, "rect1");
        GUI.Box(rect2, "rect2");
    
        Event e = Event.current;
        cid = GUIUtility.GetControlID(FocusType.Passive);
        switch (e.GetTypeForControl(cid)) {
            case EventType.MouseDown:
                if (rect1.Contains(e.mousePosition))
                    GUIUtility.hotControl = cid;
                break;
            case EventType.MouseUp:
                if (GUIUtility.hotControl == cid)
                    GUIUtility.hotControl = 0;
                break;
            case EventType.MouseDrag:
                Debug.Log("MouseDrag");
                if (GUIUtility.hotControl == cid && rect1.Contains(e.mousePosition)) {
                    DragAndDrop.PrepareStartDrag();
                    //DragAndDrop.objectReferences = new Object[] { };
                    DragAndDrop.SetGenericData("dragflag", dragData);
                    DragAndDrop.StartDrag("dragtitle");
                    offset = e.mousePosition - rect1.position;
                    drect = rect1;
                    isDraging = true;
                    e.Use();
                }
                break;
            case EventType.DragUpdated:
                Debug.Log("DragUpdated");
                drect.position = e.mousePosition - offset;
                if (rect2.Contains(e.mousePosition)) {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                    drect = rect2;
                }
                e.Use();
                break;
            case EventType.DragPerform:
                Debug.Log("DragPerform");
                DragAndDrop.AcceptDrag();
                Debug.Log("DragPerform : " + DragAndDrop.GetGenericData("dragflag"));
                e.Use();
                break;
            case EventType.DragExited:
                Debug.Log("DragExited");
                isDraging = false;
                if (GUIUtility.hotControl == cid)
                    GUIUtility.hotControl = 0;
                e.Use();
                break;
        }
    
        if (isDraging) {
            EditorGUI.DrawRect(drect, col);
        }
    }

    事件调用顺序
    这里写图片描述

  • 相关阅读:
    转载 消灭程序员需要百年吗?(重要参考)
    转载的一篇,代码规范
    自改的删除数据库中所有外键语句
    [转]批量禁用外键后,清空表数据
    我的分组分页查询语句
    Yii 分页方法总结
    25个Apache性能优化技巧推荐
    浅谈MindSpore的动态Shape
    C++开发总结 A
    Linux环境下开发常用命令汇总 A
  • 原文地址:https://www.cnblogs.com/CloudLiu/p/10746063.html
Copyright © 2011-2022 走看看