- Home /
Why do you use Coroutines and how do you use them?
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:
yield return null
Answer by Pharan · Sep 04, 2015 at 08:24 PM
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.
What about when you're just doing regular coding like a player movement script would it make it faster or would it be better to put it in a method and then called the method in update, Like this:
void Update()
{
StayInArea ();
}
void StayInArea()
{
if(move.position.x >= 7.82f)
{
move.position = new Vector2( 7.82f, transform.position.y);
}
if(move.position.x <= -7.82f)
{
move.position = new Vector2(-7.82f, transform.position.y);
}
if(move.position.y >= 4.82f)
{
move.position = new Vector2(move.position.x, 4.82f);
}
if(move.position.y <= -4.82f)
{
move.position = new Vector2(move.position.x, -4.82f);
}
}
}
Your answer
Follow this Question
Related Questions
Powerup issue - Speed 1 Answer
IEnumerator's did not read "bool" after yield return new WaitForSeconds. 1 Answer
Why isn't this IEnumerator getting called? 1 Answer
Multiple Cars not working 1 Answer
Make a laser flickering. 1 Answer