For loop returning nil

Hi
I have a basic “render distance” script that uses a while true loop to always run and then a for loop to loop through all the objects in a folder and check if they are too far away from player’s camera and if so they disappear. The problem is that for some reason the loop returns this:

attempt to index nil with 'Position'  -  Client - chunkRenderDistance:29

Whole script:

local changeRenderDistanceEvent = game.ReplicatedStorage.changeRenderDistance
local loadedChunks = workspace.loadedChunks
local plr = game.Players.LocalPlayer

local renderDistance = 1000
local eventCooldown = false

local function changeChunkVisibility(chunk, state)
	for i,v in ipairs(chunk:GetChildren()) do
		if v:IsA("BasePart") then
			if state == true then
				v.Transparency = 0
			else
				v.Transparency = 1
			end
		end
	end
end

local function eventCooldownWait()
	eventCooldown = true
	wait(1)
	eventCooldown = false
end

while true do
	for i,v in ipairs(loadedChunks:GetChildren()) do
		if v then
			local distance = (workspace.Camera.CFrame.Position - v.PrimaryPart.Position).Magnitude
			if distance > renderDistance then
				changeChunkVisibility(v, false)
			else
				changeChunkVisibility(v, true)
			end
		end
	end

	changeRenderDistanceEvent.Event:Connect(function(newRenderDistance)
		if eventCooldown == false and tonumber(newRenderDistance) then
			renderDistance = newRenderDistance
			eventCooldownWait()
		end
	end)
	wait(0.2)
end

I tried putting an if statment before the for loop which looked something like this:

local loadedChunk = v or loadedChunks:WaitForChild(v)
if loadedChunk then

But it didn’t help.

Does every model in the container that loadedChunks is referencing have a PrimaryPart set?

1 Like

Yes they all do, I put an if statement so that if v doesn’t have a primary Part it will tell me v’s name and it did a bunch of times but after checking it all had the primary Part. Btw I am cloning a model from replicated storage and putting it in the loadedChunks folder.

Then I don’t see why you’re getting an error, because any CFrame will always have the Position property.

You’re referencing workspace.Camera but the client uses workspace.CurrentCamera. Try changing it to “CurrentCamera” and it should work

1 Like