How to fix the Character is nil when leaving the game?

Hello!

In my script I have made a for loop where it loops through everything in the player’s character and checks if there is a tool when the player leaves the game.

Since there is no character when the player leaves the game, it is nil and won’t work.

Is there any way to fix this?

Players.PlayerRemoving:Connect(function(client)
	task.wait()
	local key = "client_" .. client.UserId
	tools[client] = { }

	local Character = client.Character
	local Backpack = client.Backpack


	for X, item in Character:GetChildren() do
		if not item:IsA("Tool") then continue end
		if item:IsA("Tool") then
			print(item.Name)
			table.insert(tools[client], item.Name)
		end

	end	

You can’t. You’ll need to have the tools returned to the player’s backpack immediately upon death or the removal of the player’s character.

Humanoid.Died
Player.CharacterRemoving
Humanoid:UnequipTools

I did make something like it before. Is there anything wrong with this?

player.CharacterRemoving:Connect(function(plr)
	local Char = plr.Character:GetChildren()
	for i, item in Char do
		
		if item:IsA("Tool") then
			print("item is a tool")
			local itemClone = item:Clone()
			itemClone.Parent = plr.Backpack
			itemClone.Name = item.Name
			
			item:Destroy()
			RemoveSoldItem:FireServer(item.Name, XPValue)
		end
		
	end
end)

CharacterRemoving gives the argument character instead of player, which might solv it