was learning about coroutines and im now wondering, what are the main situations i should use them in?
I dont think i should just replace every function in my code to use them so im just wondering.
was learning about coroutines and im now wondering, what are the main situations i should use them in?
I dont think i should just replace every function in my code to use them so im just wondering.
it makes multiple tasks at the same time while playing the script
Example:
in a tower defense game you have Waves
But the Mobs don’t spawn at the same time that’s why we use coroutine
If you don’t know when or where then you should probably avoid using them altogether.
This is a fairly bad example.
local Workspace = workspace
for _, Mob in ipairs(MobFolder:GetChildren()) do
local MobClone = Mob:Clone()
MobClone.Parent = Workspace
end
It’d be more likely for there to be a delay between spawns, in which case alternate threads would be redundant.
Isn’t that the same as I said?
You just explained it in the code.
You’d just add pauses in the loop, a coroutine wouldn’t be necessary. If you need iterations of the loop to run concurrently then you’d use one of the available ‘task’ library functions instead.
One shouldn’t use coroutines for the sake of using coroutines, they should only be used when completely necessary.
Yea, but then how would i learn what they do, the best cases to use them in, ect.
not sure if this is what you meant but like something like this?
function MobSpawn()
for _, Mob in ipairs(MobFolder:GetChildren()) do
local MobClone = Mob:Clone()
MobClone.Parent = Workspace
coroutine.yield()
end
end
local A = coroutine.wrap(MobSpawn)
coroutine.resume(A)
task.wait(2)
coroutine.resume(A)
ig it would just spawn the next mob in order after pauseing for a bit
(edit)
the main thing i was thinking it was used for is running code after loops
like
local D = coroutine.create(function()
while task.wait() do
print("Printing")
end
end)
coroutine.resume(D)
print("continued")
-- or whatever code so on, maybe future loops idk