Trying to clone multiple tools to make them into one (stacking items)

1. What do you want to achieve?
So im making a game where you have wood but its a tool. The tool has an attribute in it called “quantity”. I am trying to make it so that you can stack the wood together. In this script i tried to get all the tools in the backpack with a for loop and add all the amounts and create a clone of the tool with the amounts added up and then deleting all of the wood which was used to make the stack
image_2024-07-16_232933808

2. What is the issue?
And before you look at the script, YES I KNOW ITS PROBABLY BAD AND LAZY. i just dont know how to approach this as i am a beginner scripter. so basically when ever the script finds a tool it adds the amount and clones it but then it deletes the clone so you never end up with the stacked item.

local gui = script.Parent.Parent
local player = gui.Parent.Parent
local button = script.Parent

button.Activated:Connect(function()
local stackAmount = 0

	for i, v in pairs(player.Backpack:GetChildren()) do
		if v:GetAttribute("quantity") then
			stackAmount += v:GetAttribute("quantity")

			task.wait(0.1)
			v:Destroy()
			
			local newItem = v:Clone()
			newItem.Parent = player.Backpack
			newItem:SetAttribute("quantity", stackAmount)
			
		end	
	end	
end)

and i dont want to just put a folder in the player and put all the material values in there because i want to be able to share resources with other people as well

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    Idk i just gave up. this problem is pretty niche (and stupid) so i couldnt find anything to help me
1 Like

Have you tried destroying the tool AFTER cloning it? It might be because the script can’t find a tool to clone, since it has been destroyed.

1 Like

yea i tried to do that but it always deletes the clone.
the problem isnt that the script cant find tool to clone its that the clone is always getting deleted so you dont get the stacked item

I would try storing the items and their respective stack amounts in a dictionary. Then, if the item name is inside the dictionary, add their stack amount. Finally, I would clone the item and give it to the player.

I would check if they already have the tool in their inventory. If they don’t, then clone a new tool else add 1 to the existing tool’s quantity attribute. Also I recommend keeping track of people’s inventories on the server, preferably through tables (or OOP if you’re up for the challenge) instead of attributes.

ok ill try that when i get on my pc