Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Problem with cloning tools to the backpack, after death it clones several of the same tool, why?

Hey, this script should equip a tool and it works, you can also unequip. But after the player have died, when you try to equip a tool again it clones 2 of the same tool. If you die another time it clones 3 tools of the the same tool and it keeps going like this. Does anyone know what could be the problem?

SS = game:GetService("ServerStorage")
game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(char)
		player:WaitForChild("ShopValues")
		local gearValue = player.ShopValues:FindFirstChild("GearName")
		local bp = player:FindFirstChild("Backpack")
	local PG = SS:FindFirstChild("Gear"):GetChildren()	
		local PE = SS:FindFirstChild("Gear")

		gearValue.Changed:Connect(function(val)
			for i,v in pairs(PG) do
				print("WhatTheCool?")
				if gearValue.Value == "" and db == true then
					db = false
					if bp:FindFirstChild("GEAR") ~= nil then
						bp.GEAR:Destroy()
					end
				
				elseif gearValue.Value == v.Name and db == true then	
					db = false
					if bp:FindFirstChild("GEAR") ~= nil then
						bp.GEAR:Destroy()
					end
					local clone = v:Clone()
					clone.Name = "GEAR"
					clone.Parent = player:FindFirstChild("Backpack")				
				end
			end	
		end)
	end)
end)

If you have any questions please ask me, thanks :) /Xsodar

1 answer

✓ Accepted answer

You are attaching multiple event listeners in event listeners. It is okay for attaching player.CharacterAdded in game.Players.PlayerAdded because PlayerAdded only runs once per player. But with your gearValue.Changed event, it runs multiple times because the first time the event listener is attached, it listens for the gearValue to change. The second time when your character is added, the game attached yet ANOTHER gearValue.Changed event so that the two event listeners would run in sync of each other. The solution of this would be disconnect the event listener when the character dies using :Disconnect() (research it if you are unsure of how to use it) or you can stop attaching so many event listeners to the gearValue every time your character is added into the game (instead of putting gearValue.Changed in the player.CharacterAdded event, consider putting it outside the codeblock so that it doesn't make multiple event listeners).

EDIT: Here's the code:

game.Players.PlayerAdded:Connect(function(player)
	local gearValue = -- Where your gearValue is
	gearValue.Changed:Connect(function()
		-- Do something idk
	end)
	player.CharacterAdded:Connect(function()
		-- Character is added
	end)
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.