Need help with a drag and drop inventory system

Godot Version

v4.1.2.stable.mono.official [399c9dc39]

Question

I’m trying to create a drag and drop inventory system for my point and click game but there’s one small problem. While I can move my item between item slots the moment I drag it anywhere else the item immediately disappears. How can I fix this?

Here’s the code (I would upload a video but it won’t let me):

extends TextureRect

func _get_drag_data(at_position): #Creates a preview from current texture
var preview_texture = TextureRect.new()

preview_texture.texture = texture
preview_texture.expand_mode = 1
preview_texture.size = Vector2(65,65)

var preview = Control.new()
preview.add_child(preview_texture)


set_drag_preview(preview)
texture = null #Removes the current texture to indicate the item has been picked up

return preview_texture.texture

func _can_drop_data(at_position, data):
return data is Texture2D

func _drop_data(at_position, data):
texture = data

1 Like

Try using this to check if the item is dragged and dropped successfully:

func _notification(what):	

	if what == NOTIFICATION_DRAG_END:
        # This make sure that the drag-and-drop operation is complete

		if not is_drag_successful():
			# When the item is dragged with the "get_drag_data" function, try 
            # storing the previous slot and the previous item that is dragged by the player

			var prev_item = Global.some_item
            var prev_slot = Global.some_slot


			# Undo slot if player fails dragging or dropping
			
			prev_slot.item = prev_item
			prev_slot.amount = prev_item.amount

            # Call whatever function you use to update the slots

Of course, you should change the process of undoing the slot according to the way you handle drag-and-drop operations. (The script assumes that the inventory slot and item have their own class and that the slot’s amount is stored with a variable.)

1 Like

Thanks a lot, unfortunately I ended using a different system for my game but thanks for your suggestion anyway.