Why am I getting the error "attempt to index nil"

I’m working on my Plot Saving Script but when I do for I, obj in pairs(plot.PlacedObjects:GetChildren()) it says PlacedObjects is a nil value but all the plots do have a folder called Placed Objects. Here’s a part of my script for context:

THIS IS NOT THE WHOLE ENTIRE SCRIPT! ONLY THE ERROR PART

local DS = game:GetService("DataStoreService")
local Plrs = game:GetService("Players")
local PlotSave = DS:GetDataStore("PlotSave")

local plot

local function GetPlot(plr)
	for i, plt in pairs(workspace.Plots:GetChildren()) do
		if plt then
			if plt.Plot.Owner.Value == plr then
				plot = workspace.Plots:FindFirstChild(plt.Name)
			end
		end
	end
end
local function Save(plr)
	local Key = "plr-"..plr.UserId
	
	local save = {}
	
	wait()
	for i, obj in pairs(plot.PlacedObjects:GetChildren()) do
		if obj then
			table.insert(save, {
				["Name"] = obj.Name,
				
				["CFS"] = {
					["X"] = obj.PrimaryPart.CFrame.X,
					["Y"] = obj.PrimaryPart.CFrame.Y,
					["Z"] = obj.PrimaryPart.CFrame.Z,
					["R"] = obj.PrimaryPart.Orientation.Y
				}
			})
		end
	end

And here’s my workspace with the plots:

SavePlot - Roblox Studio 9_24_2020 3_07_21 PM (2)

1 Like

‘Attempt to index nil’ is an error that occurs when you try and refer to a non-existing value.
Consider debbugging your code to find when the error is occuring, so you can alter and fix it.

The bug is happening during the function save when i do for i obj in pairs plot.PlacedObjects…

The placed Objects exists but the script is not recognizing it

Implying the folders are pre-placed by you and not a script
why dont you try to redefine plot before you attempt to get the PlacedObjects children

Ok I’ll try that since I preplaced the folders

In that case, there may not be any errors in the code you provided. Do some thorough testing before making a post on the DevForums :+1:
For now there’s not much I can really help with, but;

• Make sure the folder you are referring to is accessible from the script. This means make sure it doesn’t exist on the client, and is being called for by the server.

• Run the game and play around in the server-mode.

• Reference the folder using WaitForChild instead of directly referencing it. It might be as simple as not existing yet.

Good luck!

I would recommend using :WaitForChild() to load anything that is pre-placed or may not necessarily exist when the script runs. This will yield the script until either the instance does exist, or until a specified time has passed which can be provided with the function.

The script still has the error in the output and PlacedObjects do exist on the server.