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 6 years ago
Edited 6 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:

01tool = script.Parent
02 
03local plr = game.Players.LocalPlayer
04local mouse = plr:GetMouse()
05 
06Fire = false
07equip = false
08 
09tool.Equipped:connect(function()
10    equip = true
11 
12    mouse.Button1Down:connect(function(mouse)
13        Fire = true
14        if equip and Fire == true then
15            print("ok")
View all 23 lines...

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 — 6y
0
Its disconnecting on Unequipped, and i tried it out with Activated.. its still the same. jj888jakub1 0 — 6y
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 — 6y
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 — 6y

1 answer

Log in to vote
0
Answered by 6 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:

1tool.Equipped:Connect( function ()
2    -- No, don't do this with this event
3    mouse.Button1Down:Connect( function ()
4 
5    end)
6end)

You should instead have it like the following code:

01local hasEquipped = false;
02 
03tool.Equipped:Connect( function ()
04    -- Ok, change some booleans and other variables if necessary
05    hasEquipped = true;
06end)
07 
08tool.Unequipped:Connect( function ()
09    -- Ok, change the variable back
10    hasEquipped = false;
11end)
12 
13mouse.Button1Down:Connect( function ()
14    -- Ok, make sure the user has equipped the tool
15    if hasEquipped == true then
16        print("Boom boom!");
17    end
18end)
0
I would mention that tool.Activated can just do all those lines for you Vulkarin 581 — 6y
Ad

Answer this question