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

Is this data store missing anything? Also how do I save a leaderstat?

Asked by 7 years ago

Is this data store missing anything? Also how do I save a leaderstat? Do I use PlayerStatManager:ChangeStat(player)?

local PlayerStatManager = {}

local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("PlayerData")

local AUTOSAVE_INTERVAL = 64

local DATASTORE_RETRIES = 3

local sessionData = {}

function PlayerStatManager:ChangeStat(player, statName, changeValue)
    sessionData[player][statName] = sessionData[player][statName] + changeValue
end

local function dataStoreRetry(dataStoreFunction)
    local tries = 0
    local success = true
    local data = nil
    repeat
        tries = tries + 1
        success = pcall(function() data = dataStoreFunction() end)
        if not success then wait(1) end
    until tries == DATASTORE_RETRIES or success
    if not success then
        error()
    end
    return success, data
end

local function getPlayerData(player)
    return dataStoreRetry(function()
        return playerData:GetAsync(player.UserId)
    end)
end

local function savePlayerData(player)
    if sessionData[player] then
        return dataStoreRetry(function()
            return playerData:SetAsync(player.UserId, sessionData[player])
        end)
    end
end

local function setupPlayerData(player)
    local success, data = getPlayerData(player)
    if not success then
        sessionData[player] = false
    else
        if not data then
            sessionData[player] = {Level = 1}
            savePlayerData(player)
        else
            sessionData[player] = data
        end
    end
end

local function autosave()
    while wait(AUTOSAVE_INTERVAL) do
        for player, data in pairs(sessionData) do
            savePlayerData(player)
        end
    end
end

game.Players.PlayerAdded:connect(setupPlayerData)

game.Players.PlayerRemoving:connect(function(player)
    savePlayerData(player)
    sessionData[player] = nil
end)

spawn(autosave)

game.Players.PlayerAdded:connect(function(player)
    local leaderstats = Instance.new("Model", player)
    leaderstats.Name = "leaderstats"
    local experiencePoints = Instance.new("IntValue", player)
    experiencePoints.Name = "ExperiencePoints"
    local score = Instance.new("IntValue", leaderstats)
    score.Name = "Score"
    local level = Instance.new("IntValue", leaderstats)
    level.Name = "Level"
    level.Value = 1
end)
0
for the leaderstat, you would simply chanage the value which the leaderstand is showing. the value should be inside of the leaderstats. Volodymyr2004 293 — 7y

Answer this question