How to stop OnClientEvent(?) from firing multiple times?

I have a function that detects M1 inputs from the client, then it fires a remote event “m1In” to the server to create stats for a hitbox, then it fires another remote event “m1Out” back to the client. The issue here is when i tested the OnClientEvent of m1Out, the first left click seems to just give out 1 output like it should be; however on the second click, it gives the output twice, and on the third click it gives the output three times and so on. My question is how can I fix this issue cause im not sure if it’s about the inputbegan or its about the onclientevent.

Here’s my function:

local connection
function M1Detect()
	if connection == nil then
		connection = UIS.InputBegan:Connect(function(inp, gp)
			if gp then return end

			if inp.UserInputType == Enum.UserInputType.MouseButton1 then
				checkEndLag = plr:WaitForChild("PlayerStates"):WaitForChild("EndLag").Value
				if checkEndLag or m1AnimDebounce then return end

				local animID = returnM1Count(m1count, 6)
				local anim = script.M1
				anim.AnimationId = animID
				local animPlay = plr.Humanoid:LoadAnimation(anim)

				m1count += 1
				m1AnimDebounce = true
				if m1count > 5 then m1count = 1 comboEnder = true end

				M1In:FireServer(comboEnder)
				local timeTaken
				M1Out.OnClientEvent:Connect(function(size, key, offset, dur, ogTime)

					timeTaken = os.clock() - ogTime

					local box = Instance.new("Part")
					box.Parent = workspace
					box.Anchored = true
					box.CanCollide = false
					box.Size = size
					box.Transparency = 0.9
					box.Color = Color3.new(1, 0, 0)
					box.CFrame = plr.HumanoidRootPart.CFrame * CFrame.new(offset.X, offset.Y, offset.Z)

					game.Debris:AddItem(box, dur)			
				end)
				task.wait(timeTaken)
				animPlay:Play()
				animPlay.Stopped:Wait()
				if comboEnder then comboEnder = false end
				m1AnimDebounce = false
			end
		end)
	end
end```
1 Like

You need to disconnect the connection

1 Like

i tried adding a disconnect for connection at the end but it just ended up disabling the function forever, like it only detects my click once and stops

1 Like

Okay, but i’m talking about the OnClientEvent connection, if you do not ever disconnect it then every time you’ll be receiving multiple executions, cause on every click you’re connecting a new connection, so move this outside the InputBegan connection or disconnect It after it has executed.

1 Like

yea thanks bro cant believe i spent an hour looking at this :sob:

2 Likes