Drags can only be started from MouseDown or MouseDrag events

问题

为编辑器创建鼠标拖拽事件时,如果判定方式是点击鼠标左键:

private void OnMouseDown(MouseDownEvent evt)
{
    if (evt.button == (int)MouseButton.LeftMouse)
    {
        DragAndDrop.PrepareStartDrag();
        DragAndDrop.SetGenericData("BlackboardField", this);
        DragAndDrop.StartDrag("Dragging Blackboard Field.");
        evt.StopPropagation();
    }
}

会出现报错:

Drags can only be started from MouseDown or MouseDrag events.

解决方式

看一下编辑器源码:

// Start a drag operation.
public static void StartDrag(string title)
{
    if (Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseDrag)
    {
        StartDrag_Internal(title);
    }
    else
    {
        Debug.LogError("Drags can only be started from MouseDown or MouseDrag events");
    }
}

谜底就在谜面上,把判定的内容从“点击鼠标左键”改成“按下鼠标事件”即可。

把:

if (evt.button == (int)MouseButton.LeftMouse)

替换为:

if (Event.current.type == EventType.MouseDrag)

文档链接

DragAndDrop.bindings

EventType.MouseDown