Reuse a Coroutine

I have a coroutine code for the intermission part in my minigame.
The coroutine breaks when suddenly there are not enough players in the game (So the timer resets), but then it also dies which means I can’t activate the coroutine again.
How do I stop a coroutine and reuse it later?
This is the coroutine code:

local Intermission = coroutine.wrap(function()
	-- Start countdown
	countdownOn.Value = true
	
	for i = 1, 15 do
		timer.Value -= 1
		wait(1)
		if playersOnline.Value < startingPlayersAmount.Value then return end -- This breaks out from the coroutine.
	end
	
	-- Update players alive
	playersAlive.Value = playersOnline.Value
	playersAliveTable = Players:GetPlayers()
	
	-- Load map
	gameModuleScript.LoadMap()
end)
1 Like

You could make a function that wraps and calls the code each time.

function doCoroutine()
    coroutine.wrap( yourCode )()
end
1 Like

So it creates a new coroutine every time?

Yeah pretty much.

Alternatively, to be a bit less wasteful, you can do it yourself manually with coroutine.create and coroutine.resume, and then you can check the status of the coroutine using coroutine.status() to see if it’s dead. If dead, create a new coroutine using coroutine.create.

3 Likes

Sorry I was away for a bit.
So like this?

local function intermissionCoroutine()
	local Intermission = coroutine.wrap(function()
		-- Start countdown
		countdownOn.Value = true
		
		for i = 1, 15 do
			timer.Value -= 1
			wait(1)
			if playersOnline.Value < startingPlayersAmount.Value then return end
		end
		
		-- Update players alive
		playersAlive.Value = playersOnline.Value
		playersAliveTable = Players:GetPlayers()
		
		-- Load map
		gameModuleScript.LoadMap()
	end)
	Intermission()
end

And then I just call the function?

1 Like

Yeah, that looks good to me for the option of creating a new one each time.

1 Like