- Home /
Question by
KirieZ · Jul 16, 2013 at 03:10 AM ·
c#yieldyield waitforseconds
function with yield WaitForSeconds doesn't run
Hello all, I'm trying to use yield WaitForSeconds, but I'm not getting good results, my problem is that the routine where yield exists isn't executed. I'm using C#
Example: (Edited from: Overview: Coroutines & Yield)
public class example : MonoBehaviour {
void Start()
{
Example();
}
IEnumerator Do() {
print("Do now");
yield return new WaitForSeconds(2);
print("Do 2 seconds later");
}
void Example() {
Do();
print("This is printed immediately");
}
}
Example() is fully executed (that is OK) but Do() isn't (no prints). What can I do? Thanks in advance and sorry my bad english.
Comment
Best Answer
Answer by creighcl · Jul 16, 2013 at 03:27 AM
Coroutines need to be executed differently than normal functions/methods. Make sure to call Do() using StartCoroutine()
StartCoroutine(Do());
Answer by kral · Jul 16, 2013 at 03:57 AM
and your code must be like this
public class example : MonoBehaviour {
void Start()
{
Example();
}
IEnumerator Do() {
print("Do now");
yield return new WaitForSeconds(2);
print("Do 2 seconds later");
}
void Example() {
StartCoroutine(Do());
print("This is printed immediately");
}
}
Answer by Eric5h5 · Jul 16, 2013 at 03:38 AM
In C# you have to explicitly use StartCoroutine. Unityscript does not normally require it.