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)
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
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