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
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.
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!