Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Reusing a coroutine?

I am making a tower defense game. I made coroutines in order to spawn clumps of enemies simultaneously. I found that I would often run into a "dead" coroutine though, so I adjusted it to this:

spawnYellows = coroutine.create(function(burstAmount, gapEach, times, gapBursts, lastSpawner)
	while wait() do
		local i = 0
		while i < times do -- Start Spawns
			local x = 0
			while x < burstAmount and wait(gapEach) do -- Individuals in Burst
				local yellowBlock = game.ReplicatedStorage.EnemyTemplates.Yellow:Clone()
				yellowBlock.Name = "Enemy"
				yellowBlock.Parent = game.Workspace.Enemies
				yellowBlock.CFrame = game.Workspace.startPoint.CFrame
				yellowBlock.MovementScript.Disabled = false	
				x = x + 1
			end
			wait(gapBursts)
			i = i + 1
		end
		if lastSpawner == true then
			wait(2)
			isSpawning = false
		end
		coroutine.yield()
	end
end)

But the coroutine never yields. It loops infinitely, but it doesn't crash the game. I bumped this like 8 times on ROBLOX's Scripters forum, but people there don't seem to be interested in helping e.e

1 comment

0

The accept answer is below the Answer's profile icon.

1 answer

✓ Accepted answer

Because wait uses coroutine.yield internally, you can't mix the two, though I'm a little fuzzy on the details.

Instead of using a coroutine, just make spawnYellows a function which immediately spawns a worker:

function spawnYellows(blahblah)
	spawn(function()
		for i = 1, 10 do
			wait(3)
			-- do other stuff
		end
	end)
end

This discussion is preserved as it was. New answers, comments, and votes are closed.