Hey there, I have a function for my racing game where it calculates how many seconds behind other racers are after finishing. I want to have a countdown start in another function, but I want the rest of the code in my main function to continue running after that countdown is called, how can I accomplish that?
How would I go about making a coroutine out of my function? More importantly how do I fire that function once inside of the coroutine, because I tried and it didn’t work.
local myFunction = coroutine.wrap(function()
--Do some stuff
end)
myFunction() --Does not yield
--Do other stuff while the coroutine is running too.
You should use coroutine.resume
.
-- Some main code here
coroutine.resume(coroutine.create(function()
-- Special function code here
end))
-- Some more main code here
spawn(function()
---function code
end)
OR if you want to call the function later:
local theFunction = spawn(function()
---function code
end)
theFunction()
Use the new task library, it’s more enclined with the scheduler.
Use Task.spawn() instead of the normal spawn(), and same for task.wait(n) instead of normal wait(n)
I keep trying it and nothing is happening in the do some stuff section
Maybe there is something else going on with the code your running.
Here is a countdown example. The coroutine method runs the countdown. After its called there is a while loop that does other stuff while the countdown runs. Put this into a new script and do a test run. You’ll see the timer countdown in the output and every 2 secs a warning from the other loop.
task.wait(5)
local timer = tick() + 25
local CountDown = coroutine.wrap(function()
while(timer)do
if(timer >= tick())then
print(timer - tick())
else
print("DONE SON!")
timer = nil
end
task.wait()
end
end)
CountDown()
while(timer)do
task.wait(2)
warn("I'm Doing other stuff too!")
end
So I am firing the function inside another function would that affect it at all? Instead of right below.
A coroutine can be fired anywhere. If your skiddish about showing your script you can DM me. But I won’t be able to really help without seeing exactly how your doing it.
Excellent answer. Finally understand coroutines and how they work!
it was already being called with myFunction()
oh sorry, my bad… (characters)