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

How would i fix this DataStore script? First DataStore.

Asked by 4 years ago

So i'm making a game that requires saving but i cant find out how to make a working DataStore, I got this script from Alvinblox on Youtube but it still doesn't work.

local DataStoreService = game:GetService("DataStoreService")

local MyDataStore = DataStoreService:GetDataStore('MyDataStore')





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

    local cash = Instance.new("NumberValue")
    cash.Name = 'Cash'
    cash.Parent = stats


    local data
    local success, errormessage = pcall(function()
        MyDataStore:GetAsync(player.UserId.."-cash")
    end)

    if success then
        cash.Value = data
    else
            print('error')
            print(errormessage)
    end



end)

game.Players.PlayerRemoving:Connect(function(player)


    local success, errormessage = pcall(function()
    MyDataStore:SetAsync(player.UserId.."-cash",player.leaderstats.Cash.Value)
    end)
    if success then
        print('Saved')
    else
            print("Error")
    end

end)

What am i doing wrong?

Note - This is a server script in ServerScriptService

Thanks for reading.

0
What error does it show? AM910sk 22 — 4y
0
No errors it just doesn't work. EllaTheFloofyFox 106 — 4y
0
DataStores needs to be enabled on game settings to work on studio. Do it works on the real game? Leamir 3138 — 4y

1 answer

Log in to vote
1
Answered by 4 years ago

I think it doesn't work because you didn't add an if statement asking if there was data. It wouldn't work because the player wouldn't have any data, so their cash would be equal to nil. Try this:

local DataStoreService = game:GetService("DataStoreService")

local MyDataStore = DataStoreService:GetDataStore('MyDataStore')





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

    local cash = Instance.new("NumberValue")
    cash.Name = 'Cash'
    cash.Parent = stats


    local data
    local success, errormessage = pcall(function()
        MyDataStore:GetAsync(player.UserId.."-cash")
    end)

    if success then
    if data then
            cash.Value = data
    end
    else
            print('error')
            warn(errormessage)
    end



end)

game.Players.PlayerRemoving:Connect(function(player)


    local success, errormessage = pcall(function()
    MyDataStore:SetAsync(player.UserId.."-cash",player.leaderstats.Cash.Value)
    end)
    if success then
        print('Saved')
    else
            print("Error")
        warn(errormessage)
    end

end)

If that doesn't work, then it means you haven't enabled API Services in your game.

Ad

Answer this question