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

Data Persistance/Store help?

Asked by
iLegitus 130
9 years ago

So,Im completely new to this,So if i want to make a new game and i want a specific item,Such as the player's current weapon (And other owned weapons),To be saved to his data,So when he comes again he does not need to buy them again,How would i do so? Im aware of data keys somewhere,But if someone can give me a rough aspect of how i would do this,Then much appriciated.

1 answer

Log in to vote
2
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
9 years ago

I strongly suggest using DataStores for this

Since DataStores are limited to being unable to save Instances, you'll just need to save.. say a table full of strings with the weapon names and have those weapons in ServerStorage. So then when the player leaves you iterate through their backpack, save the table with all those names.. then when a player enters check if they have a key, if they do then load up the table and iterate through ServerStorage finding any matching names and cloning along the way(:

NOTE: DataStores are only Accessible through ServerScripts.

--Define the DataStore
local ds = game:GetService('DataStoreService'):GetDataStore('WeaponData')

--PlayerAdded event for when players enter
game.Players.PlayerAdded:connect(function(plr)
    --The Potential key in DataStores.. may return nil.
    local key = tostring(plr.userId).."_weapons"
    --Get the data, if nil then use an empty table
    local data = ds:GetAsync(key) or {}
    --Iterate through the table
    for i,v in pairs(data) do
        --If a weapon matches, clone it.
        local weapon = game.ServerStorage:FindFirstChild(tostring(v))
        if weapon then
            weapon:Clone().Parent = plr.Backpack
        end
    end
end)

--PlayerRemoving event for when players leave
game.Players.PlayerRemoving:connect(function(plr)
    --Define a table, and the key to save to
    local weps = {}
    local key = tostring(plr.userId).."_weapons"
    --Iterate through their backpack, insert strings into table
    for i,v in pairs(plr.Backpack:GetChildren()) do
        table.insert(weps,v.Name)
    end
    --If there's already data, we want to use UpdateAsync, otherwise use SetAsync
    local data = ds:GetAsync(key)
    if data then
        ds:UpdateAsync(key,function(old) return weps end)
    else
        ds:SetAsync(key,weps)
    end
end
2
And to access a DataStore through a LocalScript, look into RemoteFunctions. Muoshuu 580 — 9y
0
^ Goulstem 8144 — 9y
0
Ty iLegitus 130 — 9y
Ad

Answer this question