Coroutine problem...

Hello. I am trying to make it so that when a button is pressed down a value increase for a few seconds and then decrease. But when I try to do this, I get an error that says when it says update cannot be a coroutine, how can I do what I want?.

function Update ()
{
    if(Input.GetButtonDown( "Fire1" ))
    {
        speed = 60; 
        yield WaitForSeconds (2);
        speed = 40;
    }
}

Thanks

You cannot use a yield in the Update function. I'm still trying to think of a way around this though.

Consider using CoUpdate, an alternative approach of using Update that support yield instructions. I think this is a common enough problem that has been asked several times so I'll add this link to related questions.

Using the above mentioned CoUpdate, you can make your code as such;

function CoUpdate () : IEnumerator
{
    if(Input.GetButtonDown( "Fire1" ))
    {
        speed = 60; 
        yield WaitForSeconds (2);
        speed = 40;
    }
}

Update can't yield sadly.

You could use Invoke to call another function after 2 seconds. Also use CancelInvoke to cancel any pending calls if user presses rapidly. This has the effect that the user can keep "boosting" by holding down or tapping the button. The net effect is that after 2 seconds of button release, DecreaseSpeed is called.

function Update()
{
    if(Input.GetButtonDown("Fire1"))
    {
        speed = 60; 

        CancelInvoke("DecreaseSpeed");
        Invoke("DecreaseSpeed", 2);
    }
}

function DecreaseSpeed()
{
    speed = 40;
}

Or if you still want to play around with coroutines, you can do it from Start such that:

function Start()
{
    while(true)
    {
        if(Input.GetButtonDown("Fire1"))
        {
            speed = 60; 
            yield WaitForSeconds(2);
            speed = 40;
        }
        else
        {
            yield;
        }
    }
}

Or maybe even move this all into a separate function that is initialized in Start:

function Start()
{
    StartCoroutine("HandleInput");
}

function HandleInput()
{
    while(true)
    {
        if(Input.GetButtonDown("Fire1"))
        {
            speed = 60; 
            yield WaitForSeconds(2);
            speed = 40;
        }
        else
        {
            yield;
        }
    }
}