In my script that saves the player’s inventory, if you hold a tool while leaving the game that tool doesn’t save. How can I fix this?
I’ve tried to search up some YouTube tutorials and looking on other posts related to this on the devforum, but I haven’t found any answers yet. Please help me fix this.
local dss = game:GetService("DataStoreService")
local toolsDS = dss:GetDataStore("ToolsData")
local toolsFolder = game.ServerStorage.Items
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 data, 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
plr.CharacterAdded:Connect(function(char)
local humanoid = char:WaitForChild("Humanoid")
if humanoid then
local toolInHand = humanoid:FindFirstChildOfClass("Tool")
if toolInHand then
toolInHand.Parent = plr.Backpack
else
print('no tool found in the character')
end
end
end)
plr.CharacterRemoving:Connect(function(char)
local humanoid = char:FindFirstChild("Humanoid")
if humanoid then
humanoid:UnequipTools()
end
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 plr.Character then
for _, tool in pairs(plr.Character:GetChildren()) do
if tool:IsA("Tool") then
toolsOwned[tool.Name] = (toolsOwned[tool.Name] or 0) + 1
end
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
end)