Why does tool.Equipped fire few times?

There’s a variable tool, whenever a tool was added into the character, var tool will change to the tool equipped. When it’s unequipped, it will change tool back to nil.
However, seems that the equip keep stacking, did something went wrong on the code logic?
https://gyazo.com/439f17e755738e0e3a412f21de71765c

local tool

game.Players.LocalPlayer.Character.ChildAdded:Connect(function(child)
	if child:IsA("Tool") then 
		tool = child
				
		tool.Unequipped:Connect(function()
			tool = nil
		end)
		tool.Equipped:Connect(function()
			print(tool)
		end)
	end
end)

Try using this code:

local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:wait()

local tool

char.ChildAdded:Connect(function(child)
	if child:IsA("Tool") then
        tool = child
	end
end)

char.ChildRemoved:Connect(function(child)
	if child:IsA("Tool") then
		print('child removed')
		tool = nil
	end
end)

You are listening for tool.Equipped every time a tool is placed in the player’s character. This means that every time you equip a tool which you have already added a connection to, it will add another one. This is the cause of tool.Equipped firing multiple times in your code. To fix this, instead of using tool.Equipped and tool.Unequipped I would listen to when a tool is added and removed from the character. Here is how you would do it:

local Players = game:GetService("Players")

local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()

local tool

character.ChildAdded:Connect(function(child)
	if child:IsA("Tool") then 
		tool = child
		print(tool)
	end
end)

character.ChildRemoved:Connect(function(child)
	if child:IsA("Tool") then
		tool = nil
	end
end)
3 Likes