Tools only save once

Hey everyone! I recently made a script that saves the players backpack to the DataStore. I don’t know much about DataStore so I used a tutorial I found on Youtube. My problem is it only saves a tool once. When I have e.g. 2 swords in my backpack and then I rejoin the game, I only get one sword. How do I fix this? Thank you for reading!

local DatastoreService = game:GetService("DataStoreService")
local SaveTools = DatastoreService:GetDataStore("SaveTools")
local toolfolder = game:GetService("ServerStorage"):FindFirstChild("SpawnTools")

game.Players.PlayerAdded:Connect(function(playeradded)
	local tooldata = SaveTools:GetAsync(playeradded.UserId)
	local backpack = playeradded:WaitForChild("Backpack")
	if tooldata ~= nil then
		for i, v in pairs(tooldata) do
			if toolfolder:FindFirstChild(v) and backpack:FindFirstChild(v) == nil then
				toolfolder[v]:Clone().Parent = backpack
			end
		end
	end
	
	playeradded.CharacterRemoving:Connect(function(Character)
		Character:WaitForChild("Humanoid"):UnequipTools()
	end)
end)

game.Players.PlayerRemoving:Connect(function(playerleft)
	local tooltable = {}
	
	for i, v in pairs(playerleft.Backpack:GetChildren()) do
		table.insert(tooltable,v.Name)
	end
	if tooltable ~= nil then
		SaveTools:SetAsync(playerleft.UserId,tooltable)
	end
end)
1 Like

I think the problem is that when you equip a tool, the tool get removed from the backpack. You are saving only the backpack tools.

Try this code:

local DatastoreService = game:GetService(“DataStoreService”)
local SaveTools = DatastoreService:GetDataStore(“SaveTools”)
local toolfolder = game:GetService(“ServerStorage”):FindFirstChild(“SpawnTools”)

game.Players.PlayerAdded:Connect(function(playeradded)
local tooldata = SaveTools:GetAsync(playeradded.UserId)
local backpack = playeradded:WaitForChild(“Backpack”)
if tooldata ~= nil then
for i, v in pairs(tooldata) do
if toolfolder:FindFirstChild(v) and backpack:FindFirstChild(v) == nil then
toolfolder[v]:Clone().Parent = backpack
end
end
end

playeradded.CharacterRemoving:Connect(function(Character)
	Character:WaitForChild("Humanoid"):UnequipTools()
end)

end)

game.Players.PlayerRemoving:Connect(function(playerleft)
playerleft.Character.Humanoid:UnequipTools()
local tooltable = {}

for i, v in pairs(playerleft.Backpack:GetChildren()) do
	table.insert(tooltable,v.Name)
end
if tooltable ~= nil then
	SaveTools:SetAsync(playerleft.UserId,tooltable)
end

end)

That’s not the problem. It also does’t save two of the same tools if they both are in the Backpack.

The problem is this line,

The if statement is checking to see if there is already a tool with that name in the backpack. Just change the line to:

if toolfolder:FindFirstChild(v) then
1 Like

Thank you! It finally worked :slight_smile:

1 Like