Security Camera script won't work because of a number value problem

I have a Security camera script that is supposed to go through the cameras when pressing a button to go to the next or the last one you were on. for some reason the maxindex number value is set to 0, when it should be 18, and I do not know how to fix it without just typing the number. This is a small issue that just breaks the whole script and it’s frustrating me.

local gui = script.Parent
local lastBtn = gui:WaitForChild("Last")
local nextBtn = gui:WaitForChild("Next")
local label = gui:WaitForChild("CamNo")

local camera = workspace.CurrentCamera

local cameraPartsFolder = workspace.SecCamParts
local cameraParts = cameraPartsFolder:GetChildren()
local index = 1
local maxIndex = #cameraParts -- For some reason, When I write it like this, it prints 0 instead of 18
print(maxIndex)

function updateCamera()
	camera.CFrame = cameraPartsFolder:FindFirstChild(index).CFrame
	label.Text = index
end

function nextCam()
	index += 1
	if index > maxIndex then
		index = 1
	end
	print(index)
	updateCamera()
end

function lastCam()
	index -= 1
	if index < 1 then
		index = maxIndex
	end
	print(index)
	updateCamera()
end

lastBtn.MouseButton1Click:Connect(lastCam)
nextBtn.MouseButton1Click:Connect(nextCam)

gui:GetPropertyChangedSignal("Enabled"):Connect(function()
	if gui.Enabled then
		camera.CameraType = Enum.CameraType.Scriptable
		updateCamera()
	end
end)

Thank you for reading, any help would be greatly valuable :slight_smile:

check the ‘cameraPartsFolder’, sometimes it’s empty.

I am thinking the script runs before the folder gets populated. To test add a long wait at the beginning,
3+ seconds.

I tried that and it seemed to work, then I tried using WaitForChild instead and the script is working perfectly fine now, Thank you! :grinning: