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

Script for data store saving doesnt work, spelling is correct (probably)?

Asked by 3 years ago

Ima be honest, I DONT HAVE ANY IDEA WHY ITS NOT WORKING, I checked my spelling, could find anything wrong. If you have any idea what can be wrong, feel free to comment. also the script is in server script service and yes, I have API turned on

local DS = game:GetService("DataStoreService"):GetDataStore("SaveData")
game.Players.PlayerAdded:Connect(function(plr)
    wait()
    local plrkey = "id_"..plr.userId
    local save1 = plr.leaderstats.Cash

    local GetSaved = DS:GetAsync(plrkey)
    if GetSaved then
        save1.Value = GetSaved[1]
    else
        local NumberForSaving = {save1.Value}
        DS:GetAsync(plrkey,NumberForSaving)
    end
end)

game.Players.PlayerRemoving:Connect(function(plr)
    DS:SetAsync("id_"..plr.userId, {plr.leaderstats.Cash.Value})
end)
0
Have you already created the leaderstats folder? Soban06 410 — 3y
0
wot error say BulletproofVast 1033 — 3y
0
What part doesn't work exactly? BabanizPROcuk 49 — 3y

1 answer

Log in to vote
0
Answered by
Soban06 410 Moderation Voter
3 years ago

This is how you would implement it properly:

local DS = game:GetService("DataStoreService"):GetDataStore("SaveData")

game.Players.PlayerAdded:Connect(function(plr)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = plr

    local Cash = Instance.new("IntValue")
    Cash.Name = "Cash"
    Cash.Parent = leaderstats

    local data -- We make an empty variable

    local success, errormessage = pcall(function() -- We should always wrap it in a pcall
        data = DS:GetAsync(plr.UserId) -- Now we load it
    end)

    if success and data then
        Cash.Value = data.Cash
    else
        warn("Error: "..tostring(errormessage))
    end

end)

game.Players.PlayerRemoving:Connect(function(plr)
    local success, errormessage = pcall(function()
        local data = {
            Cash = plr.leaderstats.Cash.Value;
        }

        DS:SetAsync(plr.UserId, data)
    end)

    if success then
        print("Data successfully saved for "..plr.Name)
    else
        warn("Error: "..tostring(errormessage))
    end
end)

Hope it helps.

Ad

Answer this question