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

How would I save a players inventory?

Asked by 6 years ago

I made an inventory system that basically works by a player purchasing something and it being cloned from the Replicated Storage into a GUI which has UIGridLayout in it to position them, but I want to know if there's a better solution than having a bool value such as (ownsitem_1, ownsitem_2...) because as of now doing that would be tedious.

1 answer

Log in to vote
0
Answered by 6 years ago

Ok so I have considerable experience with inventories, I use them all the time. The best way I believe to do this is by using a folder to either store the data needed with named data objects like so - - when the player joins you can clone this to the player like so -

game.Players.PlayerAdded:connect(function(plr)
    local newFolder = game.ServerStorage.Inventory:Clone()
    newFolder.Parent = plr
end)

You would want to load the data into the folder, this can be done with datastores as so -

local DSS = game:GetService("DataStoreService")
local invStore = DSS:GetDataStore("inv")

game.Players.PlayerAdded:connect(function(plr)
    local newFolder = game.ServerStorage.Inventory:Clone()
    newFolder .Parent = plr
    local plrData = invStore:GetAsync("USER_"..plr.UserId)
    --Then to test if the data exists
    if plrData then
        --Player has data
        for index,value in pairs(newFolder:GetChildren()) do
            if plrData[value.Name] then
                value.Value = plrData[value.Name]
            end
        end
    end
end)

This should load the data into the folder from the datastore, now you want to be able to save. This is simple enough -

game.Players.PlayerRemoving:connect(function(plr)
    local data ={}
    for index,invData in pairs(plr.Inventory:GetChildren()) do
        data[invData.Name] = invData.Value
    end
    invStore:SetAsync("USER_"..plr.UserId, data)
end

Now the data should load and save. You can edit the data easily enough, for example -

plr.Inventory.Stone.Value = 100
--or
plr.Inventory.Fly.Value = true

I hope I have helped and if there is something broken just ask!

0
So i'm assuming I would just clone objects into the folder right? VeryDarkDev 47 — 6y
0
No you put the objects in the folder in studio AuthenticOakChair 68 — 6y
Ad

Answer this question