RemoteEvent.OnClientEvent:Connect() Triggers for all previous :Fire()

Ok, I have a bunch of npcs, too much to run all at once on the server. So, I have the server keep track of a bit of data and a remote event that fires to all clients when a npcs goal position updates.

I then limit the client to view only the closest bunch of these npcs and only have listeners (onClientEvents) connected to the remote events of the relevant npcs, when the bunch of relevant npcs change I re-connect the listeners.

Problem: Apparently re-connecting a listener to a remote event that has fired in the past will fire again for all previous fires (that haven’t yet been recieved).

Here’s a simplified example:

-- Server Side Script
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local event = ReplicatedStorage.RemoteEvent

while wait(0.5) do
	event:FireAllClients()
end
-- Client Side Script
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local event = ReplicatedStorage.RemoteEvent

wait(5)

event.OnClientEvent:Connect(function()
	print(".")
end)

-- As soon as the wait(5) ends it prints "." x10
-- After which it prints "." at the expected rate of 1 per 0.5 seconds.

My goal is to eliminate the first batch of x10. Only listen for the fires until after the connection is made.

Let me know if you need any information I’ve left out.

While Loops process every tick while a condition is true.
if you want to wait before firing once to all clients then

wait(0.5)
event:FireAllClient()

The while loop was there to simulate the server making NPC movement decisions and then firing those decisions to the client, which will happen multiple times. It is supposed to fire multiple times.

In my example the client waits 5 seconds before a connection is made, and the server fires every 0.5 seconds. I would expect the client to only notice the Fire()'s that happen after the connection is made, however it seems that all 10 fires that happen before the connection was made still goes through.

Well yeh, this happens due to behaviour of remotes. Afaik, remotes calls do queue up so a wait(x) wouldn’t prevent the remotes from being recieved regardless of the wait. What I suggest doing is using a variable to act as a flag for when the remote should do it’s thing.

local allowToContinue = false
local connection = event.OnClientEvent:Connect(function()
	if allowToContinue then
		print(".")
	end
end)

wait(5)
allowToContinue = true
1 Like

I also ran into this problem recently and found a very good video that expands on the answer provided by @Xx_FROSTBITExX, which I will link below for anyone who wants to better understand this feature.