How to call a coroutine before an animation? (JS or C#)

Hi there,

I’ve been having issues with calling coroutines since I started coding. I’m sort of picking scripting up as I go, but this is something that I simply can’t make sense of, and there’s no clear examples on how to use it in my situation.

What I’m trying to do:

function Update (); {


if (Input.GetKey (KeyCode.Space))
		{
			//Wait for .5 seconds so that the model has time to wind up before he                
            //actually jumps
        WaitForSeconds(.5);
        animation.CrossFade("jump");
		}
}

From the documentation I’m reading, I have to start a coroutine so that I can call it, but I can’t use it inside the update function, so I have to create a whole new function just for my one animation? That makes no sense, but if that’s the easiest way to wait half a second, can someone show me the proper formatting to do so?

So you want to call the coroutine to make the animation starts later. You cannot run a coroutine from Update because it cannot be yielded.

var waitForJump : boolean = false;
function Update (){
       if (Input.GetKey (KeyCode.Space) && !waitforJump)
       {
            waitForJump = true;
            Jump();
       }
}

function Jump(){
     var timer:float = 0f;  
     while(timer < 0.5f){
         timer += Time.deltaTime;
         yield;
     }
     animation.CrossFade("jump");
     waitForJump = false;
}

the boolean makes sure you cannot call the coroutine many time in a row.

Try this:

C#:

void Update()
{

       if (Input.GetKey (KeyCode.Space))
       {
        StartCoroutine(Wait());
        animation.CrossFade("jump");
       }
}

IEnumerator Wait()
{
  yield return new WaitForSeconds(5);
}