PlayerRemoving Event Not Firing Fast Enough

So I’ve been working on a datastore script I made a while back, and I wanted to add a function that saved the player’s progress when they left the server. Even though it uses the same basic code as the other methods of saving data I’ve used (manual and autosaving), it doesn’t work. After some research, I’ve come to the conclusion that the event does fire, it just stops on line 3 here as it doesn’t have enough time to finish before the player leaves. Any help it appreciated!

game.Players.PlayerRemoving:Connect(function(Player : Player)
	game.ReplicatedStorage:WaitForChild("savingConnector"):FireClient(Player)
	game.ReplicatedStorage:WaitForChild("dataToServer").OnServerEvent:Connect(function(plr, info) --This remote event does not have enough time to execute and it stops here!
		print(info)
		playerStuff[Player.UserId].Data.Tokens = info.Tokens
		local function autosavePlayerData(information)
			playerStuff[Player.UserId]:SaveData(information)
		end
		coroutine.wrap(autosavePlayerData)(info)
		playerStuff[Player.UserId] = nil
	end)
end)

Your issue here lies in the fact that remote events take 0.1-0.5 seconds to actually go through depending on the client connection.

What I’m 90% sure is happening is the player is getting removed before the event actually finishes firing and so then the local scripts get removed and there is nothing to resolve the event.

Another blaring issue, you are retrieving data from the client. An exploiter can modify the local script so it returns an impossible amount of “FrenzyTokens” (say math.huge) and then they will get that amount when they rejoin as you are blindly trusting the client.

1 Like

use game:BindToClose() to stop the game from closing before your script is done

1 Like

Like @paetemc2 said, use bind to close. Here is an example. Not the greatest way to use BindToClose, but it works at least… lol:

game:BindToClose(function()
    task.wait(75) --// Waits 75 seconds after the last player leaves the game to shutdown the server.
end)

This should be in a server script in ServerScriptService.

How could I prevent this, then?

Get the data on the server and send all of the data you need to the client with a RemoteEvent.

2 Likes