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

How do I use DataStore?

I have 2 scripts that use DataStore one that gives players their cash from their last play when they join and one that saves their cash when they leave. However these scripts aren't working and I wish to know why.

PLAYER JOIN:

local Data = game:GetService("DataStoreService"):GetDataStore("ServerMoney")

game.Players.PlayerAdded:connect(function(plr)
	
local stats = Instance.new("IntValue",plr)
stats.Name = "leaderstats"
stats.Value = 0

local Cash = Instance.new("IntValue",stats)
Cash.Name = "Cash"
stats.Value = 0

local key = "Player-"..plr.userId

local SavedValues = Data:GetAsync(key)

if SavedValues then
	Cash.Value = SavedValues[1]	
else
	local ToSave = {Cash.Value}
	Data:SetAsync(key, ToSave)
end
end)

PLAYER LEAVE:

local Data = game:GetService("DataStoreService"):GetDataStore("ServerMoney")

game.OnClose = function()
game.Players.PlayerRemoving:connect(function(plr)
	if plr:FindFirstChild("leaderstats")then
		if plr.leaderstats:FindFirstChild("Cash")then
			local key = "Player-"..plr.userID
			
			local ToSave = {plr.leaderstats.Cash.Value}
			
			Data:SetAsync(key, ToSave)
		end
	end
end)
end

1 answer

Because you are connecting the game.Players.PlayerRemoving event within game.OnClose, all of that code will only be executed AFTER the server closes. Taking game.OnClose out entirely should fix that.

As a side note, you should generally use Data:UpdateAsync(k, v) instead of Data:SetAsync(k, v) because UpdateAsync is guaranteed to do what you tell it, even if you call multiple updates on the same key. If you have multiple SetAsyncs, they could overwrite one another.

1 comment

0

Nope. It did not work.

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