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:
01 | tool = script.Parent |
02 |
03 | local plr = game.Players.LocalPlayer |
04 | local mouse = plr:GetMouse() |
05 |
06 | Fire = false |
07 | equip = false |
08 |
09 | tool.Equipped:connect( function () |
10 | equip = true |
11 |
12 | mouse.Button 1 Down:connect( function (mouse) |
13 | Fire = true |
14 | if equip and Fire = = true then |
15 | print ( "ok" ) |
help?
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:
1 | tool.Equipped:Connect( function () |
2 | -- No, don't do this with this event |
3 | mouse.Button 1 Down:Connect( function () |
4 |
5 | end ) |
6 | end ) |
You should instead have it like the following code:
01 | local hasEquipped = false ; |
02 |
03 | tool.Equipped:Connect( function () |
04 | -- Ok, change some booleans and other variables if necessary |
05 | hasEquipped = true ; |
06 | end ) |
07 |
08 | tool.Unequipped:Connect( function () |
09 | -- Ok, change the variable back |
10 | hasEquipped = false ; |
11 | end ) |
12 |
13 | mouse.Button 1 Down:Connect( function () |
14 | -- Ok, make sure the user has equipped the tool |
15 | if hasEquipped = = true then |
16 | print ( "Boom boom!" ); |
17 | end |
18 | end ) |