My tools don't save sometimes

This is my save script inside the serverscriptservice. It’s from a youtube tutorial.

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("Plrs_"..playeradded.UserId)
	local backpack = playeradded:WaitForChild("Backpack")
	if tooldata ~= nil then
		for i, v in pairs(tooldata) do
			if toolfolder:FindFirstChild(v) 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("Plrs_"..playerleft.UserId,tooltable)
	end
end)

Mostly it works but sometimes none of the tools save and when the player joins back everything is gone.

1 Like

have you looked into BindToClose yet?

I would assume that the player’s backpack has a tendency to sometimes be removed before you can fetch it? although idk since you do check if tooltable ~= nil

You should use pcalls when using datastores. Also, the PlayerRemoving event does not fire everytime in studio, better test it in game or use BindToClose.

local DatastoreService = game:GetService("DataStoreService")
local SaveTools = DatastoreService:GetDataStore("SaveTools")

local success, err = pcall(function()
     SaveTools:SetAsync("Plrs_"..playerleft.UserId,tooltable)
end)
 
if success then
     print("data stored!")
else
     print(err)
end

This is how you can wrap the function in a pcall