Hello, I’m starting to learn how to use Coroutines but I’m confused. Firstly I don’t understand how they make your game more “streamlined”. Also I’m not sure how I should use if someone could give a me basic example that would be great. Also what is this for at the end:
Consider the situation where you want a script to do something, wait for a while, and then do something else, wait for a few more seconds, then do something else 5 times with 1 second between them.
With coroutines, all you have to do is write:
void Start () {
StartCoroutine(SomethingRoutine());
}
IEnumerator SomethingRoutine () {
DoFirstThing();
yield return new WaitForSeconds(1f);
DoSecondThing();
yield return new WaitForSeconds(2f);
for (int i = 0; i < 5; i++) {
DoThirdThing();
yield return new WaitForSeconds(1f);
}
}
Without coroutines, you would have to add and manage timers and object states to know which step of the way it is, and fill your Update method with lots of ifs or switches. Just imagine all the things you’d need to do.
PS
yield return null just means wait for the next update before continuing.