Automatic Gun slowing in firerate

I’ve added two automatic weapons to my game as experiments, but for some reason they slow down and speed up in firerate almost randomly. I’ve looked at microprofiler and there are no spikes around when the gun gets slower. I’ve also checked out script performance and realized that my blood script had a lot wasted resources, so I turned down the ammount. Still slows down, even while in a single player test. I honestly have no idea, please help.

Mouse.Button1Down:Connect(function()
		if equipped == false then return end

		fire = true

		while fire do
			
			script.Parent.RemoteEvent:FireServer(Mouse.Hit.p)

			wait(script.Parent.Settings.Cooldown.Value)
			
			Mouse.Button1Up:Connect(function()
				fire = false
			end)
			
			
		end
	end)

This happens because you connect the Button1Up event to a function numerous times inside the loop without disconnecting it. You can go about this by taking the event out of the loop, and preferably out of the other event, like so:

local fire = false
local cooldown = script.Parent.Settings.Cooldown
local remote = script.Parent.RemoteEvent

Mouse.Button1Down:Connect(function()
	if equipped == false then return end

	fire = true
	while fire do
		remote:FireServer(Mouse.Hit.p)
		task.wait(cooldown.Value)
	end
end)

Mouse.Button1Up:Connect(function()
	fire = false
end)

An alternative to this would be to move the Button1Up event inside Button1Down event, but disconnecting it immediately, like this:

Alternative
local fire = false
local cooldown = script.Parent.Settings.Cooldown
local remote = script.Parent.RemoteEvent

Mouse.Button1Down:Connect(function()
	if equipped == false then return end

    local connection
    connection = Mouse.Button1Up:Connect(function()
	    fire = false
        connection:Disconnect()
    end)

	fire = true
	while fire do
		remote:FireServer(Mouse.Hit.p)
		task.wait(cooldown.Value)
	end
end)
2 Likes