Saving DataStore Error

local function create_table(plr)
	local player_stats = {}
	
	for _, folder in pairs(script:GetChildren()) do
		if folder:IsA("Folder") then
			local fc = plr:FindFirstChild(folder.Name)
			for _, stat in pairs(fc:GetChildren()) do -- for _, stat in pairs(plr:FindFirstChild(folder.Name):GetChildren()) do
				--if stat:IsA("StringValue") and stat:IsA("BoolValue") and stat:IsA("NumberValue") then
					player_stats[stat.Name] = stat.Value
				--end
			end
		end
	end
	
	return player_stats
end

game.Players.PlayerRemoving:Connect(function(plr)
	local player_stats = create_table(plr)
	
	local success, err = pcall(function()
		local key = plr.UserId
		myDataStore:SetAsync(key, player_stats)
	end)
	
	if success then
		print("Saved data correctly")
	else
		warn(err)
	end
end)

When the player leaves the game, it says error to findfirstchild
local fc = plr:FindFirstChild(folder.Name)

Anyone know why this an error?

Can you provide me with the following details so I can help you better:

:white_small_square: What line this error is on
:white_small_square: The exact error

It this line

local fc = plr:FindFirstChild(folder.Name)

It says index nil to find folder

You are currently looping through the children of the script to find a folder, is the folder your looking for in the script?

Yeah it inside the script but in the script I parent it to the player.

Hey, are you ok with posting the full script? You probably shouldn’t have a datastore script in the player btw.

Okay so apparently you are trying to look for a folder inside the script. I believe that shouldn’t be necessary. You are using for _, folder in pairs(script:GetChildren()) do. Here, the “folder” should be the folder you are looking for. If you still want to find the “folder” inside the script which is inside the player you can do this:

local fc = script:FindFirstChild(folder.Name)

Though if you are trying to find a folder with the same name but parented to the player instead of the script, this line should work fine. local fc = plr:FindFirstChild(folder.Name)