Problem with drag and drop system

  1. What do you want to achieve? Keep it simple and clear!
    I am currently making a inventory system with a drag and drop feature where you can drag a slot that has an item to another slot to transfer the item to that slot.

  2. What is the issue? Include screenshots / videos if possible!
    It works but its kinda broken. when you click on the slot that has an item, it transfers that item to every other slot you click.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I can’t figure out how to figure out how to fix it. I tried changing how the dragging system works but it just breaks the whole script even more.

Workspace:
image

Script:

--LocalScript
local UIS = game:GetService("UserInputService")

--
local dragging
local dragInput
local dragStart
local startPos
--
local TargetSlot
local Mouse = game.Players.LocalPlayer:GetMouse()
--



for i, v in pairs(script.Parent:GetChildren()) do
	if v:IsA('ImageButton') then
		v.InputBegan:Connect(function(input)
			if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then
				local draggedSlot = v:Clone()
				local ParentSlot = v
				draggedSlot.Parent  = script.Parent
				draggedSlot:ClearAllChildren()
				
				dragStart = input.Position
				startPos = v.Position
				dragging = true

				input.Changed:Connect(function()
					if input.UserInputState == Enum.UserInputState.End then
						dragging = false
						draggedSlot:Destroy()
						TargetSlot = game.Players.LocalPlayer.PlayerGui:GetGuiObjectsAtPosition(Mouse.X, Mouse.Y)
						for _, value in pairs(TargetSlot) do
							if value:IsA('ImageButton') then
								if value.Image == "rbxassetid://0" then
									value.Image = ParentSlot.Image
									ParentSlot.Image = "rbxassetid://0"
								end
							end
						end
					end	
				end)
				
				v.InputChanged:Connect(function(input)
					if input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Touch then
						dragInput = input
					end
				end)

				UIS.InputChanged:Connect(function(input)
					if input == dragInput and dragging then
						local delta = input.Position - dragStart
						draggedSlot.Position = UDim2.new(startPos.X.Scale, startPos.X.Offset + delta.X, startPos.Y.Scale, startPos.Y.Offset + delta.Y)
					end
				end)
				
			end
		end)
	end
end

Make a boolean so that the script knows if you have something picked or not, I see you already have one called dragged but it’s not used correctly (or used for something else), in this line:

You should make it require dragging to be false and it get’s set to true after you choose it, and after when you drop the thing to another slot, set dragging to false again

1 Like