Update() can not be a coroutine

i get this error “Update() can not be a coroutine” this happens to me all the time how do i go about fixing this, here is my script;

 function Update() {
     if(Input.GetKeyDown("space"))
     yield WaitForSeconds(1);
         animation.Play ("jump_2");
 }

any help or amendments would be great

thanks

3 Answers

3

You can’t do that in Update function, as the error says it can’t be coroutine. As instead create a custom coroutine function and call it on your space key. Click here to check how to. You might also want to add some sort of cooldown countdown then or something.

Yet if you badly want that all to act in Update function then use deltatime and a variable that will count down your time, something like that:

float timer = 1f;
bool start = false;
void Update() 
{
    if (start)
    {
        timer -= Time.deltaTime;
        if (timer <= 0)
        {
            start = false;
            timer = 1f;
            animation.Play("jump_2");
        }
    }
    if (Input.GetKeyDown("space") && !start)
    {
        start = true;
    }
}

cheers but i get two error which shouldn't exist? Assets/Standard Assets/Scripts/scripts/jump-space-animation.js(1,7): UCE0001: ';' expected. Insert a semicolon at the end. Assets/Standard Assets/Scripts/scripts/jump-space-animation.js(2,6): UCE0001: ';' expected. Insert a semicolon at the end.

–

Where do you get those errors?

–

what do you mean where?

–

Post the code where you get errors...I hope you won't say that you've copy-pasted my example with deltatime in c# to your javascript.

–

i am not familiar with c#

–

yield WaitForSeconds cannot be used under update. Try putting your jumping segment in a separate fuction and have the input line in the update funcion activate it

If you want to use WaitForSeconds you’ll have to call a coroutine.
In your case, it’d be something along these lines:

function Update() {
  if(Input.GetKeyDown("space"))
      StartCoroutine(PlayAnim());
}

IEnumerator PlayAnim(){
    yield return new WaitForSeconds(1);
    animation.Play ("jump_2");
}

i get one error jump-space-animation.js(7,11): UCE0001: ';' expected. Insert a semicolon at the end.

–