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

Why does my coins saving system not save?

Asked by 6 years ago
DataStore = game:GetService("DataStoreService"):GetDataStore("Coins")

game.Players.PlayerAdded:Connect(function(Player)
local Key = "user_" .. Player.userId
local x = Instance.new("NumberValue",Player)
x.Name = "Coins"
if DataStore:GetAsync(Key)then
    x.Value = DataStore:GetAsync(Key)
else do
    DataStore:SetAsync(Key,0)
    end
end
end)

game.Players.PlayerDisconnecting:Connect(function(Player)
    local Key = "user_" .. Player.userId
    DataStore:SetAsync(Key,Player.Coins.Value)
end)
0
No error messages :/ ANDREW50060 1 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

It's a really messy code.

1) Update your script

2) PlayerRemoving and disconnecting are okay, but shouldn't be your only saves

3) It's UserId, not userId --> edit, this would have worked and it might still, but it's deprecated

4) Use pcall!

5) Use WaitForChild

6) The second param of instance.new is also deprecated (parent)!

DataStore = game:GetService("DataStoreService"):GetDataStore("Coins")

game.Players.PlayerAdded:Connect(function(Player)
    local Key = "user_" .. Player.UserId
    local x = Instance.new("NumberValue")
    x.Name = "Coins"
    x.Value = DataStore:GetAsync(Key) or 0
    x.Parent = Player
end)

while wait(10) do
    local success, message = pcall(function()
        for index, plr in pairs(game.Players:GetPlayers()) do
            local Key = "user_" .. plr.UserId
            DataStore:SetAsync(Key, plr:WaitForChild('Coins').Value)
        end
    end)

    if not success then
        print('warning, datastore error: '..message)
    end
end

If this still doesn't work, there can be a few causes

1) You're in studio and you don't have API access enabled

2) I made a typo

3) Coins doesn't exist

4) Something else

Also, I added 'or 0' because it might never have saved before! (and it's easier than checking if it's nil

If you still see any error or it doesn't work, just ask :)

Ad

Answer this question