So, I have a gun tool. It's meant to reload when you press R. However, when you put the tool away and take it out again, it will fire the function twice, then three times, and so on. How would I prevent this?
Here's my code.
tool.Equipped:connect(function(mouse) --Tool equipped toolEquipped = true mouse.Icon = "http://www.roblox.com/asset?id=" .. mouseIcon local character = player.Character local Humanoid = character.Humanoid animTrack = character.Humanoid:LoadAnimation(holdGun) animTrack:Play() local ammoDisplay = player.PlayerGui:WaitForChild("ammoDisplay") ammoDisplay.Frame.ammo.Text = scriptLoaded .. "/" .. scriptUnloaded game:GetService("UserInputService").InputBegan:Connect(onKeyPress) end)
This is really simple. You need to use :Disconnect(). For an example of this, you should do
local f = game.Workspace.Part.Changed:Connect(function() print('touch') end) wait(10) print('Disconnecting...') f:Disconnect()
For your code, you would do
tool.Equipped:connect(function(mouse) --Tool equipped toolEquipped = true mouse.Icon = "http://www.roblox.com/asset?id=" .. mouseIcon local character = player.Character local Humanoid = character.Humanoid animTrack = character.Humanoid:LoadAnimation(holdGun) animTrack:Play() local ammoDisplay = player.PlayerGui:WaitForChild("ammoDisplay") ammoDisplay.Frame.ammo.Text = scriptLoaded .. "/" .. scriptUnloaded f = game:GetService("UserInputService").InputBegan:Connect(onKeyPress) end) tool.Unequipped:Connect(function() f:Disconnect() end)
:Disconnect just stops the function from being called from an event.
Hope this helps!