To whoever who wants to have a proper inventory saving system, here it is.
-
Saves the tool even if you are holding it while leaving the game
-
Can save multiple tools with the same name
-
IMPORTANT: Create a folder in ServerStorage called “Items”, put all the tools you want to be able to be saved in this folder.
Make a script in ServerScriptService, and paste this code inside of the script:
local dss = game:GetService("DataStoreService")
local toolsDS = dss:GetDataStore("ToolsData")
local toolsFolder = game.ServerStorage.Items
-- Store currently held tools in this table
local playerTools = {}
game.Players.PlayerAdded:Connect(function(plr)
local toolsSaved = {}
local success, err = pcall(function()
toolsSaved = toolsDS:GetAsync(plr.UserId .. "-tools") or {}
end)
if not success then
plr:Kick("There was an error while loading your inventory, please join the game again.")
warn("Error loading tools for", plr.Name, ":", err)
return
end
-- Prevents duplication
plr.Backpack:ClearAllChildren()
plr.StarterGear:ClearAllChildren()
for toolName, toolCount in pairs(toolsSaved) do
if toolsFolder:FindFirstChild(toolName) then
for i = 1, toolCount do
local clonedTool = toolsFolder[toolName]:Clone()
clonedTool.Parent = plr.Backpack
local starterTool = toolsFolder[toolName]:Clone()
starterTool.Parent = plr.StarterGear
end
end
end
playerTools[plr.UserId] = {}
plr.CharacterAdded:Connect(function(char)
local function updateTools()
local heldTools = {}
for _, tool in pairs(char:GetChildren()) do
if tool:IsA("Tool") then
heldTools[tool.Name] = (heldTools[tool.Name] or 0) + 1
end
end
playerTools[plr.UserId] = heldTools
end
-- track changes in the character
char.ChildAdded:Connect(updateTools)
char.ChildRemoved:Connect(updateTools)
updateTools() -- run when the character spawns
end)
end)
game.Players.PlayerRemoving:Connect(function(plr)
local toolsOwned = {}
for _, tool in pairs(plr.Backpack:GetChildren()) do
toolsOwned[tool.Name] = (toolsOwned[tool.Name] or 0) + 1
end
if playerTools[plr.UserId] then
for toolName, count in pairs(playerTools[plr.UserId]) do
toolsOwned[toolName] = (toolsOwned[toolName] or 0) + count
end
end
local success, err = pcall(function()
toolsDS:SetAsync(plr.UserId .. "-tools", toolsOwned)
end)
if not success then
warn("Error saving tools for", plr.Name, ":", err)
end
playerTools[plr.UserId] = nil
end)