UserInputService not working well with Tool.Equipped

So I got a problem, I did this script

local uis = game:GetService("UserInputService")
local isToolHeld

script.Parent.Equipped:Connect(function()
	isToolHeld = true
	uis.InputBegan:Connect(function(input)
		if (uis:GetFocusedTextBox()) then
			return;
		end
		if input.KeyCode == Enum.KeyCode.Z and isToolHeld then
			print("Pressed Z")
		end	
	end)
end)

script.Parent.Unequipped:Connect(function()
	isToolHeld = false
end)

And it’s buggy, like when I press Z when my tool is equipped, it prints but if I unequip and equip again, it will print 2x the message, and if I unequip again, and equip again, it will print 4x the message, etc…

And I’m supposed to change the print with an event that will get fired.

How can I fix that?

1 Like

it’s because you connect a new UIS connection everytime you equip it. Try this:

local uis = game:GetService("UserInputService")
local isToolHeld, UISCon

script.Parent.Equipped:Connect(function()
	isToolHeld = true
    if UISCon then UISCon:Disconnect() end
	UISCon = uis.InputBegan:Connect(function(input)
		if (uis:GetFocusedTextBox()) then
			return;
		end
		if input.KeyCode == Enum.KeyCode.Z and isToolHeld then
			print("Pressed Z")
		end	
	end)
end)

script.Parent.Unequipped:Connect(function()
	isToolHeld = false
end)
1 Like

Also if you don’t want it to fire at all when it’s unequipped then disconnect it when you unequip like this:

local uis = game:GetService("UserInputService")
local isToolHeld, UISCon

script.Parent.Equipped:Connect(function()
	isToolHeld = true
	UISCon = uis.InputBegan:Connect(function(input)
		if (uis:GetFocusedTextBox()) then
			return;
		end
		if input.KeyCode == Enum.KeyCode.Z and isToolHeld then
			print("Pressed Z")
		end	
	end)
end)

script.Parent.Unequipped:Connect(function()
	isToolHeld = false
    if UISCon then UISCon:Disconnect() end
end)
2 Likes

Thanks it works very well, this is exactly what is was looking for.

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