game.Players.PlayerAdded:Connect(function(plr)
local toolsSaved = toolsDS:GetAsync(plr.UserId .. "-tools") or {}
for i, toolSaved in pairs(toolsSaved) do
if toolsFolder:FindFirstChild(toolSaved) then
toolsFolder[toolSaved]:Clone().Parent = plr.Backpack
toolsFolder[toolSaved]:Clone().Parent = plr.StarterGear
end
end
plr.CharacterRemoving:Connect(function(char)
char.Humanoid:UnequipTools()
end)
end)
game.Players.PlayerRemoving:Connect(function(plr)
local toolsOwned = {}
for i, toolInBackpack in pairs(plr.Backpack:GetChildren()) do
table.insert(toolsOwned, toolInBackpack.Name)
end
local success, errormsg = pcall(function()
toolsDS:SetAsync(plr.UserId .. "-tools", toolsOwned)
end)
if errormsg then warn(errormsg) end
end)
First off, this script is a script to save player’s inventory.
Second, I have this unique problem where sometimes you get duplicates of the same item, and I want to check if there are duplicates (when the player joins), and if so, I want to :Destroy() them. (not all, just the duplicates, (you leave the original))
a new table called uniqueTools is introduced to keep track of the tools that have already been added to the player’s inventory. When iterating through the saved tools, if a duplicate is found, it is destroyed using the :Destroy() method.
game.Players.PlayerAdded:Connect(function(plr)
local toolsSaved = toolsDS:GetAsync(plr.UserId .. "-tools") or {}
local uniqueTools = {} -- To keep track of unique tools
for i, toolSaved in pairs(toolsSaved) do
if toolsFolder:FindFirstChild(toolSaved) then
-- Check if the tool is already added to the player's inventory
if uniqueTools[toolSaved] then
-- Duplicate found, destroy it
toolsFolder[toolSaved]:Destroy()
else
-- Add the tool to the uniqueTools table
uniqueTools[toolSaved] = true
-- Clone and add the tool to the player's inventory
toolsFolder[toolSaved]:Clone().Parent = plr.Backpack
toolsFolder[toolSaved]:Clone().Parent = plr.StarterGear
end
end
end
plr.CharacterRemoving:Connect(function(char)
char.Humanoid:UnequipTools()
end)
end)