Tool saving script not working

I followed a YT tutorial that shows you how to make a script that saves tools in a player’s inventory. But when I rejoin the game the tool does not re-appear in my inventory.

Here is the script:

local ds = game:GetService("DataStoreService"):GetDataStore("ToolSave")
game.Players.PlayerAdded:connect(function(plr)
 local key = "id-"..plr.userId
 pcall(function()
  local tools = ds:GetAsync(key)
  if tools then
   for i,v in pairs(tools) do
    local tool = game.ServerStorage.Tools:FindFirstChild(v)
    if tool then
     tool:Clone().Parent = plr:WaitForChild("Backpack")
     tool:Clone().Parent = plr:WaitForChild("StarterGear")
    end
   end
  end
 end)
end)
game.Players.PlayerRemoving:connect(function(plr)
 local key = "id-"..plr.userId
 pcall(function()
  local toolsToSave = {}
  for i,v in pairs(plr.Backpack:GetChildren()) do
   if v then
    table.insert(toolsToSave,v.Name)
   end
  end
  ds:SetAsync(key,toolsToSave)
 end)
end)

I have been having this issue for… well god knows how long, and I am dying to know how to fix this.

1 Like

It would help if you debugged your own code before taking this to a thread. Notice that your entire code is already wrapped in pcalls (which is frankly awful use of them). Due to this, if your code is experiencing errors, then you’re not going to know because the script doesn’t throw.

Attach two variables to the beginning of a pcall and print them after the end that closes it.

local success, result = pcall(function ()
    -- code here
end)
print(success, result)

This will help you identify if there is an immediate issue with your code to fix before you start doing an analysis on the rest of your code. There can be very small oversights that you aren’t seeing.

2 Likes

I don’t think you’ve considered the case of the tool being equipped at the time of leaving, in which situation the tool isn’t under the backpack but the player’s character. You might have been equipping the tool before you left, try printing the content of the backpack from your for loop

2 Likes

OH MY GOD… I can not express how ashamed / embarrassed I feel at this very moment. Thank you so much for pointing this out. I probably would have never figured this out without your help.