- Home /
C# yield WaitForSeconds not working
void Start ()
{
StartCoroutine(delay());
GoBall();
}
IEnumerator delay()
{
yield return new WaitForSeconds(2.5f);
print("Ok");
}
void GoBall()
{
int randomNum = Random.Range(0, 1);
if (randomNum <= .5)
rigidbody2D.AddForce(new Vector2(ballSpeed, 10));
else
rigidbody2D.AddForce(new Vector2(-ballSpeed, -10));
}
I cannot get WaitForSeconds to work in Unity at all. I've made sure my function returns an IEnumerator. I've started up the function with StartCoroutine(), but no luck. My ball keeps launching without any delay.
Answer by robertbu · Oct 24, 2014 at 09:18 PM
First, you can solve your problem like this:
IEnumerator Start ()
{
yield return new WaitForSeconds(2.5f);
GoBall();
}
As for why you current code does not work, you need to explore and understand the nature of a coroutine. At the point where your code where the execution hits the 'yield' statement, your coroutine returns. That means it will return and execute line 4 immediate, but it will wait the 2.5 seconds before it prints out okay.
Ah, I see. That makes sense now. Thanks for the walking me through how coroutines work. Oh, and having a working solution is a plus :). Thanks a bunch!