How to fire an event when a player is given a tool

I would like to fire an event when the player is given a tool. I’ve already tried a ChildAdded event on the backpack and it does work… but also fires when the player de-equips a tool, not what I wanted.

My current code: (local script)

local plr = game.Players.LocalPlayer

plr.CharacterAdded:Connect(function()
	local backpack = plr:WaitForChild('Backpack')
	
	backpack.ChildAdded:Connect(function()
		-- do whatever
		print('player was given a tool')
	end)
end)

I know why it the ChildAdded event fires since the tool is added back to the Backpack from the character upon de-equip. I’d just like a work-around so that it won’t fire when the player de-equips their tool.

2 Likes

You can try this and see if it fits your needs:

local plr = game.Players.LocalPlayer

plr.CharacterAdded:Connect(function()
	local backpack = plr:WaitForChild('Backpack')
	
	
	local plrCharacter = plr.Character or plr.CharacterAdded:Wait() --Get plr character
	
	local movingTool = "" --This will hold the tool removed from the plr character
	
	plrCharacter.ChildRemoved:Connect(function(child) --Detect tool removed from plr character
		if child:isA("Tool") then
			movingTool = child.Name
		end
	end)
	
	backpack.ChildAdded:Connect(function(child)
		if child.Name == movingTool then	--Checks if the added tool was removed from plr character
			print("De-equipped tool")
			movingTool = ""
		else
			print("New tool added")
			--Code
		end	
	end)
end)

This way you will be able to distinguish a new tool from tools being de equipped.

1 Like

Works like a charm, thank you very much!

1 Like

Nice! Please remember to mark the solution.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.