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

Database/saving stuff help?

Asked by
Bman8765 270 Moderation Voter
10 years ago

How do I save things like for example a player's personal variable titled money or the amount of kills they have to the database so when they join a different server that is still my game all their stats are transferred. It doesn't matter what it saves all I need is an example or some wiki links on how to do this

1 answer

Log in to vote
0
Answered by
zblox164 531 Moderation Voter
6 years ago
Edited 6 years ago

First off you need a leaderboard:

game.Players.PlayerAdded:connect(function(plr)
    local stats = Instance.new("IntValue", plr)
    stats.Name = "leaderstats" 

    local money = Instance.new("IntValue", stats)
    money.Name = "Money" -- Name of your stats
end)

After that you will need to get the DataStoreService:

local Data = game:GetService("DataStoreService"):GetDataStore("NameOfDS")

You will need to get the players key to do this you create a new local variable inside of the leaderboard. You will create another variable called saved:

local key = "plr-"..plr.userid
local saved = Data:GetAsync(key)

You need an if statement to check if saved == nil. If its not == nil then we have to load the data from before:

if Saved then
        money.Value = saved[1]
    else
        local ValuesToSave = {money.Value }
        Data:SetAsync(key, ValuesToSave)
    end

After you do that you need to create a event that saves the values when the player leaves the game:

game.Players.PlayerRemoving:connect(function(plr)
    local money = game.Players.LocalPlayer.leaderstats.Money
    local key = "plr-"..plr.userid
    local valuesToSave = {money.Value}

    Data:SetAsync(key, valuesToSave)
end)

final script:

local Data = game:GetService("DataStoreService"):GetDataStore("NameOfDS")

game.Players.PlayerAdded:connect(function(plr)
    local stats = Instance.new("IntValue", plr)
    stats.Name = "leaderstats" 

    local money = Instance.new("IntValue", stats)
    money.Name = "Money" -- Name of your stats

    local key = "plr-"..plr.userid
    local saved = Data:GetAsync(key)
        if Saved then
                money.Value = saved[1]
            else
                local ValuesToSave = {money.Value }
                Data:SetAsync(key, ValuesToSave)
        end
end)

game.Players.PlayerRemoving:connect(function(plr)
    local money = game.Players.LocalPlayer.leaderstats.Money
    local key = "plr-"..plr.userid
    local valuesToSave = {money.Value}

    Data:SetAsync(key, valuesToSave)
end)

This is just a basic version of data store but hope this helps. You can do a lot more with Data Store when you learn more about it. Just realized you posted this 3 years ago. LOL

Ad

Answer this question