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

How to save leaderstats?

Asked by 2 years ago

so I make specific value on leader stats such as kills/death/total kills I only want to save my total kills but it won't save. ``

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("KillsStats")

game.Players.PlayerAdded:Connect(function(Player)
    local Leaderstats = Instance.new("Folder", Player)
    Leaderstats.Name = "leaderstats"
    local Kill= Instance.new("IntValue", Leaderstats)
    Kill.Name = "Kills" 
    Kill.Value = 0
    local deaths = Instance.new("IntValue", Leaderstats)
    deaths.Name = "Deaths"
    deaths.Value = 0
    local Kills= Instance.new("IntValue", Leaderstats)
    Kills.Name = "Total Kills" 
    Kills.Value = 0
    Player.CharacterAdded:connect(function(char)

        local humanoid

        repeat
            humanoid = char:FindFirstChild("Humanoid")
            wait()
        until humanoid

        humanoid.Died:connect(function()

            deaths.Value = deaths.Value + 1

            local Data = DataStore:SetAsync(Player.UserId)
            if Data then
                Kills.Value = Data 
            end
        end)

        end)

    end)


game.Players.PlayerRemoving:Connect(function(Player)
    DataStore:SetAsync(Player.UserId, {
        ["Total Kills"] = Player.leaderstats.Kills.Value;})
end)

1 answer

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

Here is what most leaderstats look like: (note: this is a normal script inside ServerScriptService)

local dss = game:GetService("DataStoreService")

local ds = dss:GetDataStore("data")


function saveData(plr)


    local cash = plr.leaderstats.Cash.Value -- whatever the name of your leaderstat is.
    pcall(function()

        ds:SetAsync(plr.UserId .. "-Cash", cash)
    end)
end



game.Players.PlayerAdded:Connect(function(plr)


    local ls = Instance.new("Folder")
    ls.Name = "leaderstats"
    ls.Parent = plr

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

    local data = nil

    pcall(function()

        data = ds:GetAsync(plr.UserId .. "-Cash")
    end)

    cash.Value = data or 0
end)


game.Players.PlayerRemoving:Connect(saveData)

game:BindToClose(function()


    for i, plr in pairs(game.Players:GetPlayers()) do

        saveData(plr)
    end
end)

if this helped make sure to mark my answer as a solution, And thank you.

0
THANK YOU! jackwater0 7 — 2y
Ad

Answer this question