I just learned that coroutines are used to make multiple things work at once, but why wouldn't i just use task.spawn? I know you can use yield to pause a coroutine but you can also think of other clever ways to make a task.spawn stop at a given point? How do i when i want to let 2 ( or more) different things play at once whether to use a coroutine or a task.spawn?
#Coroutines vs task.spawn
1 messages · Page 1 of 1 (latest)
That's a very great question. It comes down to what you want to achieve, if you want to do simple tasks that doesn't need to return anything or a pause, you would use a Task.Spawn. If let's say you want to do much more complex coding, you would use a Coroutine.
Basically, you have more control when using coroutines instead or task.spawn
Q: Why wouldn't I just use task.spawn?
A: That is an awesome consideration, since you understand that both of them are functioning quite the same. Although, it depends on what you want to do in your code. Simple = task.spawn. Complex = coroutines.
Q: Task.spawn can also be stopped just like using yield to pause a coroutine?
A: While that is true, you cannot really pause task.spawn, so in that case you have less control over what you want to do.
Q: How do i when i want to let 2 ( or more) different things play at once whether to use a coroutine or a task.spawn?
A: Again, it depends on your goal. Let's say for example you want to make a passive hp regen code, in this case you would use task.spawn. But if you want to make let's say a quest system, you would use a coroutine. Why? Because it can pause and wait for the first quest to be finished, for example:
Imagine a quest where:
- Talk to an NPC.
- Go kill 5 wolves.
- Come back for a reward.
With task.spawn:
You have to constantly check: "Did they talk to the NPC? No. Okay, check again. Did they kill the wolves yet? No. Check again." This is called polling, and it's exhausting for the computer.
With coroutine:
The script runs the first line ("Talk to NPC"), then it pauses itself and goes to sleep. It stays "frozen" on that line.
The moment the player kills the 5th wolf, the game sends a signal: "Wake up!" The coroutine wakes up exactly where it left off and says, "Great job, here is your gold!"
I hope that cleared things up
Alright, thanks alot! I understand it now. Thanks for explaining it so clear!
No problem!