• 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);
        }
    }

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

  • 相关阅读:
    php 0916
    心里话
    LibreOJ 6559 小奇采药
    计蒜客 T1658 热浪
    计蒜客 T2021 飞扬的小鸟
    POJ 1276 Cash Machine
    SCU 3366 Watering Hole
    POJ 3268 Silver Cow Party
    luogu P4568 [JLOI2011]飞行路线
    POJ 1179 Polygon
  • 原文地址:https://www.cnblogs.com/CloudLiu/p/10746063.html
Copyright © 2020-2023  润新知