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

Saving data script not working and not giving an error?

Asked by 5 years ago
Edited 5 years ago

Here's the script, Also should I put the script in a local script or a normal one and where should I put it?

               local DSS = game:GetService("DataStoreService")

local datastore = DSS:GetDataStore("GeneralSaveData", "Players")

function generateDataKey(player)
    local ret = "uid_" .. player.userId
    return ret
end

function generateDataTable(player)
    local dataTable = {
        Gold= player.leaderstats.Gold.Value,
        Fishies= player.leaderstats.Fishies.Value
    }
    return dataTable
end

function saveDataForPlayer(player)
    local key = generateDataKey(player)
    local data = generateDataTable(player)
    datastore:SetAsync(key, data)
end

function inputDataToPlayer(player, data)
    player.leaderstats.Gold.Value = data.Gold
    player.leaderstats.Fishies.Value = data.Fishies
end

function loadDataForPlayer(player)
    local key = generateDataKey(player)
    local data = datastore:GetAsync(key)
    inputDataToPlayer(player, data)
end

game.Players.PlayerAdded:Connect(function(player)
    loadDataForPlayer(player) --Load first thing when they join
    player.leaderstats.Fishies.Changed:Connect(function()
        saveDataForPlayer(player) --Save the data 
    end)
end)

game.Players.PlayerRemoving:Connect(saveDataForPlayer) --Save data when the player leaves the game

1 answer

Log in to vote
0
Answered by 5 years ago

A few critiques of why it may not be working... First you are not checking to see if you actually got a Datastore element in the first place, specifically here:

function inputDataToPlayer(player, data)
    player.leaderstats.Gold.Value = data.Gold
    player.leaderstats.Fishies.Value = data.Fishies
end

function loadDataForPlayer(player)
    local key = generateDataKey(player)
    local data = datastore:GetAsync(key)
    inputDataToPlayer(player, data)
end

You are calling inputDataToPlayer without checking to see if data is nil, that will cause your loop to error out.

Also, here:

function saveDataForPlayer(player)
    local key = generateDataKey(player)
    local data = generateDataTable(player)
    datastore:SetAsync(key, data)
end

You COULD do SetAsync, but instead you could check to see if that particular key already exists and instead do an UpdateAsync which is much faster. If the key doesn't exist yet, then you would be forced to do a SetAsync.

Ad

Answer this question