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

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

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?

4 comments

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)

0

Its disconnecting on Unequipped, and i tried it out with Activated.. its still the same.

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

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()

1 answer

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)

1 comment

0

I would mention that tool.Activated can just do all those lines for you

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