You can write your topic however you want, but you need to answer these questions:
-
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. -
What is the issue?
I can’t figure out how
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)