Datastore error

Hello, so i just made a datastore script tha was supposed to save some values inside of a folder in the player but the output keeps on saying: ServerScriptService.DataSaving.Script:35: attempt to index nil with 'FindFirstChild
here is my script:

local datastoreservice = game:GetService("DataStoreService")

local mydata = datastoreservice:GetDataStore("firstdatastore")

game.Players.PlayerAdded:Connect(function(player)
	local data = mydata:GetAsync(player.UserId.."-test")
	
	if data then
		for i, v in pairs(data) do
			local savedvalue = Instance.new("StringValue")
			savedvalue.Name = v
			savedvalue.Parent = player.Areas
		end
	end
end)


game.Players.PlayerRemoving:Connect(function(player)
		local folder = {}
	for i, v in pairs(player:FindFirstChild("Areas"):GetChildren()) do
		table.insert(folder,v.Name)
	end
	local sucess, errormsg = pcall(function()
		mydata:SetAsync(player.UserId.."-test", folder)
	end)
	if sucess then
		print("saved!")
	else
		print("there was an error")
	end
end)

game:BindToClose(function(player)
		local folder = {}
	for i, v in pairs(player:FindFirstChild("Areas"):GetChildren()) do
		table.insert(folder,v.Name)
	end
	local sucess, errormsg = pcall(function()
		mydata:SetAsync(player.UserId.."-test", folder)
	end)
	if sucess then
		print("saved!")
	else
		print("there was an error")
	end
end)

Thank you!

The error “attempt to index nil with FindFirstChild” appears anytime a variable is nil and you try to compare it or find something with it. It’s like the following

local apple
local fruits = workspace.Fruits
apple.Parent = fruits

The variable ‘apple’ isn’t defined so it’s default value is nil. So I can’t parent it to the folder ‘fruits’ so in your case one of your variables is nil and since it is you can’t use FindFirstChild with it. Make sure your variable is defined correctly and to make sure it is you can use breakpoints or print() statements to check.

1 Like

but its already defined how can i fix this? The player have a folder inside of him.

Which function does the error take place in? Is it your PlayerAdded, PlayerRemoving, or game:BindToClose()?

playerremoving (30 characters)

I think the issue is when you call :FindFirstChild() on the player’s ‘Area’ folder it doesn’t find it. Instead in your player removing do

local areas = player:WaitForChild("Areas")
for i, v in pairs(areas:GetChildren()) do

If you want to use FindFirstChild instead of WaitForChild you can do

local areas = player:FindFirstChild("Areas")
if areas then
    for i, v in pairs(areas:GetChildren()) do

Then you’d continue with the rest of your code.

1 Like