Remote event firing but can't wait

I have no idea whether this is a bug or not, but here’s what’s going on:
I have a very simple setup, a script in ServerScriptService that runs this code:


local remote = game.ReplicatedStorage:WaitForChild("RemoteEvent")

game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function()
		remote:FireClient(player)
		print("fired")
	end)
end)

And in StarterGui I have a localscript inside a gui:

game.ReplicatedStorage.RemoteEvent.OnClientEvent:Connect(function()
	print("recieved")
	task.wait(1)
	print("waited one second")
end)

When I first run the game, the code works as expected

image_2023-07-11_164638456

But once I reset my character, it fires but doesn’t wait one second.
image_2023-07-11_164654705

Any help would be appreciated!!

Each time the event is received it calls the function from the start, whether or not the last call has finished. You need something like this:

local eventLastFired = tick() --Set to current time
local cooldown = 1 --Seconds

game.ReplicatedStorage.RemoteEvent.OnClientEvent:Connect(function()
	print("recieved")
	
	if tick() - eventLastFired < cooldown then
		print("too early! Please wait.")

		return --Cancel function
	end

	--Run the function's actual job here

	--Set timer to current time
	eventLastFired = tick()
end)

Are you ever deleting the script? I am askinf this because the last line in the output does not have a line number and scriptname like every other line. Where is the localscript located?

I don’t think this is remotely close to the issue.

Didn’t seem to work, it didn’t even print the first time

It’s inside of a ScreenGui in StarterGui. There’s nothing else in the game that should be deleting it, as far as I know.

Set the screengui resetonspawn to false most likely.

2 Likes

Worked perfectly, thank you! I wonder what causes it to still receive, if it’s getting reset.

1 Like

So I assume it’s just the order of events. The character probably get’s added a small bit before all the UI’s get reset - causing it to stop working after the ui is reset. Glad it worked!

2 Likes

It’s likely a race condition where the previous (just despawned) character’s GUI is still around to respond to the event, but has been garbage collected before the 1 second expires so never gets to the final print statement.

If in your GUI script you keep a reference to the remote event handling function, rather than making it anonymous, then you can forcibly Disconnect() it on CharacterRemoving and make sure this sort of thing doesn’t happen.

4 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.