Question about yield WaitForSeconds()

I have the following code which works well:

function moveit()
{
while (true)
{
for (i=0; i<100; i++)
{
transform.position.x = v.x+i/100.0;
yield;
}
for (i=100; i>0; i–)
{
transform.position.x = v.x+i/100.0;
yield;
}
}
}

But if I replace yield with yield WaitForSeconds() the object doesnt move but instead just jitters.
Why is that? And what would be the difference of:

yield WaitForSeconds(1);

and:

WaitForSeconds(1);
yield;

Iam having a hard time to understand the semantics of coroutines…

Try reading the documentation:
http://unity3d.com/support/documentation/ScriptReference/index.Coroutines_26_Yield.html

and:

These links should give you the answer!

I wouldnt ask if I haven’t already read the docs.
The questions I have aren’t (at least not explicitly) answered in the docs.

Iam guessing using WaiForSeconds without a prepending yield it effectively a no-op although it compiles and runs without warning.

But this doesn’t explain why my Example also is not working when using “yield WaitforSeconds(1)”. It only works correctly when using “yield” only.

WaitForSeconds is a function, that might look something like this:

function WaitForSeconds (timer : float) {
   var t = 0.0;
   while (t < timer) {
      t += Time.deltaTime;
      yield;
   }
}

If you call the function without yielding, it will still do exactly what it says, but since all it does it wait, calling without yielding won’t have any visible effect, other than giving the CPU a bit more work to do.

I’m not sure why you’d want to use WaitForSeconds in that case at all. Also your example probably doesn’t work as intended since it’s framerate-dependent.

–Eric

function Update () 
{
  print("before");
  WaitForSeconds(10);
  print("after"); 
}

“before” and “after” are printed immediately one after another, there is not wait.

I know my sample is framework dependent, it is just a testscript for me to understand how yield and WaitForSeconds really work.

Right. Read what I just posted above.

–Eric

Oh sorry, I re-read your post and now I understand what you mean.

But this doesn’t explain why my moveit()-function does not move anymore when using yield WaitForSeconds() instead of just yield.

I’m still not sure why you want to replace yield with yield WaitForSeconds in the first place. If you move something a bit and then wait for 10 seconds, of course it won’t be smooth.

–Eric