Issue: "cannot close running coroutine"

I have a NPC pathing system, for NPCs to follow a path:

	local pathing = coroutine.create(function()
	while true do
		for i = startNode,#nodes do
			local movement = module.npcMove(npc,nodes[i].CFrame)
			movement.Completed:wait()	
			battleService.checkForBattleInstance(npc)
		end
		startNode = 1
	end
end)
coroutine.resume(pathing)
activePaths[npc] = pathing

Once a battle starts, or when a enemy joins, I break the path by doing this:

module.breakPath = function(npc,run) --npc object
	if activePaths[npc] ~= nil then
		
		print(coroutine.status(activePaths[npc]))
		
		coroutine.close(activePaths[npc])
		activePaths[npc] = nil
	end
end

However I sometimes get the error cannot close running coroutine. I have tried calling coroutine.yeild but it just stalls. How can I prevent this? I need to stop the pathing so the enemy moves to the node.

Oddly, it seems to sometimes return “suspended” status, and other times return “running”.

Also, is there a better way to do a “pathing” system than this?

4 Likes