Drag and drop in a Godot editor plugin

Let's say you want to create a scene/prefab palette - maybe for filling an area with random clutter or whatever. The palette should hold a list of scenes you want to use.

Palette

To add scenes to the palette, users will want to drag and drop from the FileSystem dock.

How Godot drag/drop works

Godot editor windows/docks/containers are all ultimately Godot scenes with Control root nodes.

Control nodes have the function get_drag_data, which attaches arbitrary data to dragged items.

The FileSystem dock handily gives us scene paths, folder origin, and whether the dragged item contains files or files/dirs, in the drag data.

You can see the cpp source code for this here.

Accepting drag data

The palette is a simple ItemList node:

Palette

With the following gdscript code:

tool
extends ItemList

func can_drop_data(position, data):
  return true

func drop_data(position, data):
  var file_paths = data["files"]
  for path in file_paths:
    var item_len = get_item_count()
    add_item(path.get_file().get_basename())
    set_item_metadata(item_len, path)

tool makes the script run in the editor.

can_drop_data allows the ItemList to accept dropped items.

drop_data extracts the drop data that the FileSystem dock sets up and adds items accordingly.

In real usage you'd have to do more checking around what exactly the user has dropped onto the node.

Useful tools

I recommend using Godot Plugin Refresher to make plugin dev much easier.