Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why is the Tool Saving Script only saving the first item in the backpack and not the others?

So I am currently making an Obby. I have a shop GUI in which people can buy items if they have enough money. P.S: This is a YT tutorial. I have placed a script inside serverscriptservice which is as follows:

local ds = game:GetService("DataStoreService"):GetDataStore("ToolSavee")
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:FindFirstChild("Backpack")
     tool:Clone().Parent = plr:FindFirstChild("StarterGear")
    end
   end
  end
 end)
end)
game.Players.PlayerRemoving:connect(function(plr)
 local key = "id-"..plr.userId
  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)

But the problem is that this script is only saving the first item which the player buys e.g. If there are 2 items in the shop, and the player has enough money to buy both of them, so the first item he will buy will be stored in the backpack and if he buys the second item, the second item will be given to him.

But when the player rejoins the game, only the item he bought first will be saved not the other item.

What is wrong in this script?

Please do help.

Thanks

2 answers

It is because you forgot to call i on your table insert when the player is leaving. So that results in the loop only saving one tool.

table.insert(toolsToSave,i,v.Name)

Try changing line 22 to what I showed above and tell me the results. Hopefully this helped you.

4 comments

0

Thanks a lot!

0

No problem.

0

Oh but I just figured out that if the player buys another item it is not saved even though the first 2 are saved. Any idea?

0

If the tool is equipped it won't save. But if you want the tool to save even though it is equipped then try looking at @TheMinecraftSmart's answer.

Actually, if you were holding nothing this script would work. This is because when you are holding a tool, it is moved from your backpack to your character. Add this code inside PlayerRemoving:

local char = player.Character

if char then
	local charParts = char:GetChildren()
	for key,part in (charParts) do
		if part.IsA("Tool") then
			table.insert(toolsToSave,part)
		end
	end
end

Hope this helped!

3 comments

0

Great!

0

Do I just add it to my player removing event or should I delete my prevoius player removing event?

0

Use your player removing event, just add the code I suggested.

This discussion is preserved as it was. New answers, comments, and votes are closed.