Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why is this running multiple times?

Asked by
gitrog 326 Moderation Voter
6 years ago

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)
0
Use a debounce rilgundam 65 — 6y
0
cause u write animTrack:play() but u need to write somewhere else AnimTrack:Stop() or it loop IcyMizu 122 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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!

0
Disconnect? You probably should disconnect before my brain blows up greatneil80 2647 — 6y
0
No, you should! hiimgoodpack 2009 — 6y
Ad

Answer this question