While loop in coroutine breaking randomly

So I’m using a coroutine with a while loop inside and I’ve found that adding the most random things will cause the while loop to break or only run once.

This code is okay: (‘check will print as normal’)

local Thread1 = coroutine.create(function()
while true do
	print("check")
	for _, tycoon in pairs(game.Workspace.GameContent:GetChildren()) do
		
	end
	wait()
end
end)
coroutine.resume(Thread1)

This code is NOT okay: (‘check’ only prints once and never again)

local Thread1 = coroutine.create(function()
while true do
	print("check")
	for _, tycoon in pairs(game.Workspace.GameContent:GetChildren()) do
		for _, npc in pairs(tycoon.Pathfinding.Npcs:GetChildren()) do
			print(npc)
		end
	end
	wait()
end
end)
coroutine.resume(Thread1)

For clarification, there are no parts in the ‘npc’ folder but there will be when instanced into the game. That’s the reason why I have the loop, to constantly check. I have no idea why something so little or normal could break the loop.

I also found that doing a simple print will break the while loop. (print is below)

print(#tycoon.Pathfinding.Npcs:GetChildren())

There are no errors in the output. Could someone please tell me why this is happening?

Have you checked the code with coroutine.status()? Use a pcall with it, as I’m fairly sure courotines don’t give error messages. (Only with coroutine.status.)

Sometimes coroutines don’t give you an error message when they error. I would print your loop outside the coroutine to see what’s actually erroring.

1 Like

I now remember why I hate coroutines. :+1:

2 Likes