Client Event fires multiple times for no apparent reason

I’m testing my project, and it seems when the server fires to the client, the client fires multiple times. I am not getting any signs of the server being the issue here.

Client

workspace:WaitForChild("MainEvent").OnClientEvent:Connect(function(LeafValue)
	local Humanoid = Player.Character:FindFirstChild("Humanoid")
	local Swing = Animations.Swing
	local PlayAnim = Humanoid:LoadAnimation(Swing)
	PlayAnim:Play()
	script.Sound:Play()
	ReplicatedStorage.Datastore2Folder.EditCapacity:FireServer(true, LeafValue) -- // This fires 
end)

Server:

Event.OnServerEvent:Connect(function(Plr, Location, Hitpoints)
	print("Server")
	local Character = Plr.Character
	local Hum = Character:FindFirstChild("Humanoid")
	Location.CanCollide = false
	Location.Anchored = true
	Hum:MoveTo(Location.Position)
	Hum.MoveToFinished:Connect(function(Reached)
		print("fired")
		if Reached then
			print(Plr.Name .. " has reached the target.")
			Event:FireClient(Plr, Hitpoints)
			wait(0.5)
			Location:Destroy()
		else
			Location.CanCollide = true
			Location.Anchored = false
			print(Plr.Name .. " has not reached the target.")
		end
	end)
end)

Check to see if you’re firing the server multiple times

1 Like

You are not calling :Disconnect() on Humanoid.MoveToFinished, and therefore it could end up firing your “Event” mutliple times.

Whenever you are calling :Connect on an event - inside of an Event that will be called multiple times (as you are here), you must save the Connection as a variable, and call :Disconnect() on it as soon as you use it the first time.

For example

local finished_moving 

finished_moving = Hum.MoveToFinished:Connect(function(reached)
    finished_moving:Disconnect() -- stop it from firing the connected code more than once.
    -- do stuff
end)

if you’re feeling really spicy you could do

local reached = Hum.MoveToFinished:Wait()
-- do stuff with reached

But, I personally dislike using :Wait(), and saving connections as variables is a good habit to have. (as long as you remember to Disconnect them :sunglasses:)

7 Likes
local finished_moving -- needs to be defined before it can be used in the function to disconnect it
finished_moving = Hum.MoveToFinished:Connect(function(reached)
    finished_moving:Disconnect() -- stop it from firing the connected code more than once.
    -- do stuff
end)
2 Likes

You’re right, my mistake.

1 Like