execution order of methods and coroutine

hello everyone, my problem is i dont understand , how the coroutines work? i have a method (spakleOn()), i want to play a particle system (check) ,whenever i called method sparkleOn and i want to run this particle system for 10 sec. and then stop it…i have write two codes with the help of others ,one of them running perfectly but i dont understand why other is wrong …sorry for my poor english.



First of all I would like to appreciate the curiosity of knowing why something worked and why other didn’t.

Now, the reason is, Coroutines are “kind of” asynchronous

Meaning that, when they’re triggered, the control flow would be back to the line which triggered the coroutine, as soon as the coroutine encounters it’s first yield return *** statement.

To relate this with the code above, In your 1st example (not working as expected),

  • At line: 4, StartCoroutine(delay()); will start the Coroutine delay() and it enters the while loop (so far so good).
  • Now as it executes the yield return null statement in line:15, control flow will be back to void SparkleOn() method which triggered the coroutine.
  • And then, you know the rest of the story, as it executes the check.Stop()in line: 5, your particle system is immediately stopped.

Where as in the second example above, check.Stop() is called within the coroutine which would be executed only after 10 seconds through multiple yield return null statements.

Bonus : The below code would help you solve the problem in a much cleaner way.

IEnumerator sparkleOn() { check.Play(); yield return new WaitForSeconds(10); check.Stop(); }

And from somewhere in the code,

thanks a lot @anilhdas …now i have a clear idea of coroutine and how it works…