I have been trying to learn the basics of coroutines, and I think they are used for multithreading. The thing is that I don't understand why they are used, can someone give me an example of how they can be used in-game on anything?
COMMUNITY QUESTION
What purpose are coroutines used for? What are some examples in which coroutines are use in game?
1 answer
You are somewhat correct in that they are used for multithreading. Although they shouldn't be considered "true" multithreading.
You could for instance use them in an animation cycle, while performing some other task.
local part = game.Workspace.Part
local EndFlag = 0
coroutine.wrap(function()
while EndFlag < 1000 do
part.CFrame = part.CFrame*CFrame.new(0,.1,0)
wait()
end
end)()
--somewhere else in the script, perhaps in a function or some other logic
while EndFlag < 1000 do
--Potentially some other simultaneous animation
EndFlag = EndFlag + 10
wait()
end
Is this efficient? No not at all. I don't even recommend using this method, however I hope this gives you an idea of some of the potential use cases.
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
super easy example: 2 loops running at the same time if you do while true do twice in a single script they won't run at the same time without threading