Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Datastore won't save properly when player leaves the game?

game.Players.PlayerRemoving:Connect(function(plr)
	pcall(function()

	ParticlesToSave = { }
	ACToSave = { }
	
	for i, v in pairs(plr.Activation:GetChildren()) do
		if v.Value == "1" then
			table.insert(ParticlesToSave, v.Name)
		else
			table.insert(ACToSave, v.Name)
		end
	end
	ds:SetAsync(plr.UserId, ParticlesToSave)
	ds2:SetAsync(plr.UserId, ACToSave)
	end)
end)

When the player leaves the game, the data won't save. However, if I use a GUI to save the data, it works. Any suggestions why this does not work?

2 answers

Not sure...

But I never Save the data when they leave. Because it only saves if they actually press Leave and some users just click "X"

I Would use an event that checks and sees if the value changes. Then saves it.

Eg. A RemoteEvent.

1 comment

0

No, changed events are unnecessary. What if a OP's game has values that constantly change? Less than 6 seconds each time? I'd instead have some auto save interval every 30 seconds-1 minute or so.

This is the end of one of mine...set up a little different from yours but perhaps useful. It references "config", a ModuleScript in RS. In the ModuleScript is where it states SaveOnExit = true and AutomaticSaving = true (every 5 min but you could change that). It also uses BindToClose as you can see to save data if all servers are shutdown.

game.Players.PlayerRemoving:Connect(function(plr)
	if (not plr) then return end
	pcall(function()
		if require(config).SaveOnExit then
			SaveData(plr)
		end
	end)
end)

local ServerTimeout = 5
game:BindToClose(function() -- Lets data save if all servers shutdown
	for _,v in pairs(game.Players:GetPlayers()) do
		if (v~=nil) then SaveData(v) end
	end
	wait(ServerTimeout)
end)

Here is a portion ref the leaderstats for SaveData for their Level and Gold. As suggested by incapaz and Enomphia, there is also a Notify remote event in ReplicatedStorage so the server will know when values have been changed client side.

SaveData = function(plr)
	-- Stats
	pcall(function()
		local lstats = plr:FindFirstChild("leaderstats")
		if (lstats~=nil) then
			local level = lstats:FindFirstChild("Level")
			local gold = lstats:FindFirstChild("Gold")
			if (level~=nil) and (gold~=nil) then
				Stats:SetAsync(plr.UserId,{level.Value,gold.Value})
			end
		end

This discussion is preserved as it was. New answers, comments, and votes are closed.