Attempt to index nil with 'GetChildren'

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? I have a system that saves tools in the players inventory.

  2. What is the issue? I try to save the tools in the players character but just gives the error, attempt to index nil with ‘GetChildren’.

  3. What solutions have you tried so far? I tried to have an else statement that would save the tools through their inventory but it still gives an error.

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

game.Players.PlayerRemoving:Connect(function(player)
	local char = player.Character

	saveData(player)
	local CameraTable = {}
	
	for i,v in pairs(player.Backpack:GetChildren())do
		table.insert(CameraTable,v.Name)
	end
	for i,v in pairs(char:GetChildren())do -- line where error is
		if v:IsA("Tool") then
			print("7")
			table.insert(CameraTable,v.Name)
		else
			warn("Cannot find tool in player's character")
			for i,v in pairs(player.Backpack:GetChildren())do
				print(8)
				table.insert(CameraTable,v.Name)
			end
		end
	end
	if CameraTable ~= nil then
		PDs:SetAsync(player.UserId,CameraTable)
	end
end)

It will work in studio however it doesn’t work in the actual game.

The Character might not exist when the player leaves, so just add an if statement above the char:GetChildren() line

What should I put in the if statement. I’ve already tried this before but it still doesn’t work.

Either has dandcx said or put a:

game.Players.PlayerRemoving:Connect(function(player)
	player.CharacterRemoving:Connect(function(char)
		-- remove this local char = player.Character
		--rest of code
	end)
end)

It still doesn’t save in game but it works in studio. I don’t get the error any more.

Iterating any child/descendant of the object that is being destroyed is not something I would recommend doing on any removal event. You are going to have to accumulate this info where it can safely be indexed whether the parent of it is being destroyed or not, some folder or something, but not in the player, i.e. not inside the object that is being destroyed/removed.