Optimization script not working correctly

For some reason this code does not work with my block generator.
Blocks are usually at workspace.Chunks.Chunk.block (all are named that so the getChildren is used.)

game:GetService("RunService").Heartbeat:Connect(function()
	if game.ReplicatedStorage.loaded == true then
	local chunks = workspace.Chunks
	local i = 0
	local j = 0
	local allchunks = chunks:GetChildren()

	local chunkamount = #allchunks

	for i=0,chunkamount,1 do
		task.wait()
		--print("Started initial loop")
		--print(i)
		if allchunks[i] then
			--print("chunk exists")
			--print(allchunks[i]:GetFullName())
			local blocks = allchunks[i]:GetChildren()
			
			local blockamount = #blocks
			
			for j = 0,blockamount,1 do
				task.wait()
				if blocks[j] then
					--print("block exists")
					--print(blocks[j]:GetTouchingParts())
					--print(blocks[j]:GetFullName())
					local touch = blocks[j]:GetTouchingParts()
					local touching = #touch
					if touching > 5 then
						--print("Attempting to hide block "..blocks[j]:GetFullName().." id:"..j.."in chunk "..allchunks[i]:GetFullName().." with chid "..i)
						blocks[j].Transparency = 1
						--print(blocks[j].Transparency)
					else
						--print("Faces air somewhere")
					end
				end
			end
		end
		--print("Ended initial loop")
		end
	else
		print("Not loaded yet!")
	end 
end)
1 Like