#Inv save

1 messages · Page 1 of 1 (latest)

delicate island
#

My inventory save script currently only works when a player leaves and rejoins the game, but it resets the tools when the player dies. I want the script to also save and restore tools properly on respawn. Can someone add that in. Script below⬇️

#
local DataStoreService = game:GetService("DataStoreService")-- :nerd:
local ServerStorage = game:GetService("ServerStorage")

local player_data = DataStoreService:GetDataStore("player_data")
local tools = ServerStorage.Tools
local inventories = ServerStorage.Inventories

local function updateInventory(client)
    local inventory_folder = inventories:FindFirstChild(client.Name)
    if not inventory_folder then return end
    
    --clear original inventory
    for _, item in ipairs(inventory_folder:GetChildren()) do
        item:Destroy()
    end

    --update inventory 
    for _, tool in ipairs(client.Backpack:GetChildren()) do
        if tool:IsA("Tool") then
            local original = tools:FindFirstChild(tool.Name)
            if original then
                original:Clone().Parent = inventory_folder
            end
        end
    end
end

Players.PlayerAdded:Connect(function(client)
    local key = "client_" .. client.UserId
    local inventory = player_data:GetAsync(key) or {}

    --crates inventory folder
    local inventory_folder = Instance.new("Folder")
    inventory_folder.Name = client.Name
    inventory_folder.Parent = inventories

    for _, name in ipairs(inventory) do
        local tool = tools:FindFirstChild(name)
        if tool then
            tool:Clone().Parent = client.Backpack
            tool:Clone().Parent = inventory_folder
        end
    end
    
    --update inventory when tool is added
    client.Backpack.ChildAdded:Connect(function()
        updateInventory(client)
    end)
    
    --update inventory when tool is removed
    client.Backpack.ChildRemoved:Connect(function()
        updateInventory(client)
    end)
    
end)```
#
    local key = "client_" .. client.UserId
    local inventory_folder = inventories:FindFirstChild(client.Name)
    
    if not inventory_folder then return end

    updateInventory(client)

    local tool_names = {}
    
    for _, tool in ipairs(inventory_folder:GetChildren()) do
        table.insert(tool_names, tool.Name)
    end

    --saves the player tool data
    player_data:SetAsync(key, tool_names)
    inventory_folder:Destroy()
end)```
#

i had to split it into 2 bc of discord type limit

#

both in the same script (serverscriptservice)

zinc trout
#

@delicate island just use proflie server