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

Why is this running multiple times?

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)

2 comments

0

Use a debounce

0

cause u write animTrack:play() but u need to write somewhere else AnimTrack:Stop() or it loop

1 answer

✓ Accepted answer

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!

2 comments

0

Disconnect? You probably should disconnect before my brain blows up

0

No, you should!

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