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

When equipping more than once and firing it will do it more than once?

Asked by 5 years ago
Edited 5 years ago

im currently working on a gun and im having this weird glitch and getting literally and headache because of it.

So if you equip the tool more than once like 5 times and click it will print "ok" 5 times, idk why i am getting this...

here is the script:

tool = script.Parent

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

Fire = false
equip = false

tool.Equipped:connect(function()
    equip = true

    mouse.Button1Down:connect(function(mouse)
        Fire = true
        if equip and Fire == true then
            print("ok")
        end
    end)
end)

tool.Unequipped:connect(function(mouse)
    equip = false
    Fire = false
end)

help?

0
Because you're connecting to mouse.Button1Down on each equip and never bothering to Disconnect, you need to Disconnect the event on Unequipped (or better yet, just use tool.Activated) Vulkarin 581 — 5y
0
Its disconnecting on Unequipped, and i tried it out with Activated.. its still the same. jj888jakub1 0 — 5y
0
No, mouse.Button1Down:Connect() gets connected every single time equipped is fired. You are not disconnecting the mouse.Button1Down event, you're only running a debounce Vulkarin 581 — 5y
0
And as for activated, don't put activated inside of the tool.Equipped:Connect() (which is the exact same problem as mentioned above). You can delete everything after line 04, then do tool.Activated:Connect() Vulkarin 581 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago

This is because for each time you equip the tool, you're creating a new event listener, this is also why if you're equipping / unequipping 5 times, it will execute 5 times.

Remember that code should (almost) never have event listeners within event listeners, unless the first event listener is fired only once, as this will cause what you are experiencing right now.

The solution is to put the other event listener (mouse.Button1Down) outside of the tool.Equipped scope, this should fix your issue.

Basically, this is considered "bad code" for your current case:


tool.Equipped:Connect( function () -- No, don't do this with this event mouse.Button1Down:Connect( function () end) end)

You should instead have it like the following code:

local hasEquipped = false;

tool.Equipped:Connect( function ()
    -- Ok, change some booleans and other variables if necessary
    hasEquipped = true;
end)

tool.Unequipped:Connect( function ()
    -- Ok, change the variable back
    hasEquipped = false;
end)

mouse.Button1Down:Connect( function ()
    -- Ok, make sure the user has equipped the tool
    if hasEquipped == true then
        print("Boom boom!");
    end
end)
0
I would mention that tool.Activated can just do all those lines for you Vulkarin 581 — 5y
Ad

Answer this question