Saturday 21 February 2015

[Unity3D] Starting & stopping coroutines

Recently I was figuring out how start and stop coroutine works in Unity. And here you can find what I find out.



First things first.

What are those "Coroutines"?


They are almost same as functions but you can program them to work over time.
For example: if you'd like to tween a button or fade out any object over time you'll be able to do that only with coroutines (or very complex and strange Update... ;) ) because they are not limited to single frame like normal functions.

If you are looking for better explanation what coroutines are you can find it on the end of the post.. ;)


2 Ways To Do Coroutines


There are 2 ways to play with coroutines:

1. With string


It's most common one. You just pass name of method and it should run. Also you are able to pass single parameter to that method

Start:
StartCoroutine("DoSomething"); 
Stop: 
StopCoroutine("DoSomething");

[Important]
If you call multiple coroutines with same name than single StopCoroutine with that name will destroy them all (also started with IEnumerator).


2. With IEnumerator


There are 2 ways to do that with IEnumerators. In both you are not limited to a single parameter like in the case above which is good for some reasons.
First is just passing method to StartCoroutine();
StartCoroutine(DoSomething());

[Important]
Only way to stop such coroutine is to use StopCoroutine with it's name. See first paragraph.

And there is second way to do that. First you need assign that method to variable and than pass that variable to StartCorourine();

Start:
IEnumerator ien = DoSomething();
StartCoroutine(ien);
Stop: 
StopCoroutine(ien);

[Important]
Like in first paragraph you're able to stop multiple coroutines with single StopCoroutine with variable that were used to create those coroutines ;)




3. As Coroutine (strange fact)


StartCoroutine has return value type of Coroutine.
So if you use that value to stop coroutine it should work just perfect!

Start:
Coroutine cor = StartCoroutine(DoSomething());
Stop: 
StopCoroutine(cor);

[Important]
Well... Not really.. Coroutine stops after that but also gave us "Coroutine continue failure" error..
So it's not recommended to use that!

[Note]
StopCorourtine and StopAllCoroutines works only within single instance of the MonoBehaviour

For more information about coroutines go to Unity's documentation
 - Coroutines
 - StartCoroutine
 - StopCoroutine
 - StopAllCoroutines

No comments:

Post a Comment