Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I use DataStore?

Asked by
Nidoxs 190
8 years ago

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

Log in to vote
1
Answered by 8 years ago

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.

0
Nope. It did not work. Nidoxs 190 — 8y
Ad

Answer this question