Help with pausing and resuming coroutines

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve?
    Create a coroutine that i can pause and resume as i want, without needing to create a new one each time.

  2. What is the issue?
    I can’t figure out how :smile:

Hello fellow scripters, i come for your aid with a coroutine “problem”, quotes because it’s not an issue but i would like to understand how i can improve my code for the future because i cannot figure it out.
I have a local script that handles players flight and i wanted to have a coroutine that every 1 second they are actually flying they are rewarded XP based on their speed. I want to coroutine so this tracking is done in another thread and don’t hog the main one which im using for reproducing sounds and animations.
Below is my implementation which works, BUT i need to create and close a thread each time they start/stop flying, is there a way i can pause the coroutine when they stop flying and just resume it next time they start moving?, below the relevant code for context. Thanks!

-- Every 1 second players get XP for flying based on their speed.
local function trackFlightXp()
	while true do
		task.wait(1)
		PlayerDataManager.AddXp(PlayersService.LocalPlayer, BaseSpeed)
	end
end

local trackFlightXpCoroutine

Flymoving.Changed:Connect(function(isMoving)
	if isMoving == true then
		trackFlightXpCoroutine = coroutine.create(trackFlightXp)
		coroutine.resume(trackFlightXpCoroutine)
		flightCameraTween:Play()
		hoverAnimTrack:Stop()
		Sound1:Play()
		flyAnimTrack:Play()
		return
	end
	if isMoving == false then
		coroutine.close(trackFlightXpCoroutine)
		hoverCameraTween:Play()
		flyAnimTrack:Stop()
		Sound1:Stop()
		hoverAnimTrack:Play()
	end
end)

I think what you’re looking for is just coroutine.yield(trackFlightXpCoroutine).

2 Likes

Ah i tried that when i was messing around and what happened is that the coroutine function just sayed on the loop, it didn’t pause the thread. Maybe there is something i can modify to the actual trackFlightXp to work with the coroutine.yield(trackFlightXpCoroutine) but i cannot figure out what.

Instead of doing all of this, why not do this:

local CanTrack = false

local function trackFlightXp()
	while true do
		if not CanTrack then task.wait() continue end
	
		PlayerDataManager.AddXp(PlayersService.LocalPlayer, BaseSpeed)
		task.wait(1)
	end
end

local Thread = task.spawn(trackFlightXp) --If you want to fully close the thread

With this method, all you have to do is toggle the CanTrack variable to control tracking saving you all the coroutine shenanigans

1 Like

Ahh great idea, this makes so much more sense for what im intending to do. Thank you for the guidance!.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.