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

How to save multiple values with leaderstats & datastores?

Asked by
dxrrevn 13
3 years ago

So here's my current script:

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

game.Players.PlayerAdded:Connect(function(Player)
    local Leaderstats = Instance.new("Folder")
    Leaderstats.Name = "leaderstats"
    Leaderstats.Parent = Player

    local Clicks = Instance.new("IntValue")
    Clicks.Name = "Clicks"
    Clicks.Parent = Leaderstats

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

    local ClicksData
    local CashData

    local Success, ErrorMessage = pcall(function()
        ClicksData = DataStore:GetAsync(Player.UserId.."-ClicksData")
        CashData = DataStore:GetAsync(Player.UserId.."-CashData")
    end)

    if not Success then
        print(ErrorMessage)
    end

    if ClicksData ~= nil then
        Clicks.Value = ClicksData
    else
        Clicks.Value = 0
    end

    if CashData ~= nil then
        Cash.Value = CashData
    else
        Cash.Value = 0
    end
end)

game.Players.PlayerRemoving:Connect(function(Player)
    pcall(function()
        DataStore:SetAsync(Player.UserId.."-ClicksData", Player.leaderstats.Clicks.Value)
        DataStore:SetAsync(Player.UserId.."-CashData", Player.leaderstats.Cash.Value)
    end)
end)

Answer this question