Help with tool save script!

Hi, I have a tool-saving script and for the most part, it works great yet sometimes items do not get saved and I just think the script could be improved but I don’t know where? If I could have some help that would be great!’

Code
local DataStore = game:GetService("DataStoreService"):GetDataStore("MyDataStore")

game.Players.PlayerAdded:Connect(function(plr)

local data = DataStore:GetAsync(plr.UserId.."tools")


	local success, errorMessage = pcall(function()
		local data = DataStore:GetAsync(plr.UserId.."tools")
	
	end)



	if data ~= nil then
		for _, toolName in pairs(data) do

			local tool = game.ReplicatedStorage.Tools:FindFirstChild(toolName)

			if tool then
				local newTool = tool:Clone()
				newTool.Parent = plr.Backpack

				local newTool = tool:Clone()
				newTool.Parent = plr.StarterGear
			end
		end
	end

end)

game.Players.PlayerRemoving:Connect(function(plr)

	local toolsTable = {}

	for _, tool in pairs(plr.Backpack:GetChildren()) do
		if game.ReplicatedStorage.Tools:FindFirstChild(tool.Name) then
			table.insert(toolsTable,tool.Name)
		end
	end

	local success, errorMessage = pcall(function()
		DataStore:SetAsync(plr.UserId.."tools",toolsTable)
		DataStore:SetAsync(plr.UserId.."cash",plr.leaderstats.Cash.Value)
	end)

end)

game:BindToClose(function()
	for _, plr in pairs(game.Players:GetPlayers()) do
		local toolsTable = {}

		for _, tool in pairs(plr.Backpack:GetChildren()) do
			if game.ReplicatedStorage.Tools:FindFirstChild(tool.Name) then
				table.insert(toolsTable,tool.Name)
			end
		end

		local success, errorMessage = pcall(function()
			DataStore:SetAsync(plr.UserId,toolsTable)
		end)
	end
end)

thanks for your help :grin:

Saving a player’s tools in a DataStore isn’t really something you can do directly.

There are many ways to go about this. What you could do is organize the tools into a folder in ServerStorage. When a player leaves, get the names of all their tools and save it in an array.

Then, when the player comes back, retrieve the array and loop through it checking for what they had. Whichever tool they had, you can clone it from the folder in ServerStorage and insert it into their backpack.

2 Likes