How to disable a keypress after a certain amount of time?

I have a button that gives the player a speed boost, but I only want it to last for a short amount of time (like a second). I’m trying to use a Coroutine to make it last only a second, but it’s not working right.

My Code:

	IEnumerator SpeedUpBoost () {
		yield return new WaitForSeconds (speedUpCutoffTime);
		rigbody.velocity = new Vector2 (speed, 0);

	}

	
	// Update is called once per frame
	void Update () {
		if (updateOn == true) {
			if (Input.GetKey (moveUp)) {
				rigbody.velocity = new Vector2 (speed, 20);
			} else if (Input.GetKey(speedUp)) {
				rigbody.velocity = new Vector2 (speed, 40);
				StartCoroutine (SpeedUpBoost ());
			} else if (Input.GetKey (speedDown)) {
				rigbody.velocity = new Vector2 (speed, -20);
			} else {
				rigbody.velocity = new Vector2 (speed, 0);
			}
		}
	}

Any ideas on what to do what be super helpful! Thanks! :smiley:

WaitForSeconds will pause the coroutine, you can use WaitForEndOfFrame and Time.deltaTime to keep track of time progress. Can try something like this:

bool boostAvailable = true;

IEnumerator SpeedUpBoost () {
    updateOn = false;
    boostAvailable = false;

    float elapsed = 0f;
    while (elapsed < speedUpCutoffTime)
    {
        rigbody.velocity = new Vector2 (speed, 40);
        elapsed += Time.deltaTime;
        yield return new WaitForEndOfFrame();
    }

    updateOn = true;

    // simple cooldown, prevent boost for some time
    // if an item makes the boost available, then it can set boostAvailable to true instead.
    yield return new WaitForSeconds(5f);
    boostAvailable = true;
}


// Update is called once per frame
void Update () {
    if (updateOn == true) {
        if (Input.GetKey (moveUp)) {
            rigbody.velocity = new Vector2 (speed, 20);
        } else if (Input.GetKey(speedUp) && boostAvailable) {
            StartCoroutine(SpeedUpBoost());
        } else if (Input.GetKey (speedDown)) {
            rigbody.velocity = new Vector2 (speed, -20);
        } else {
            rigbody.velocity = new Vector2 (speed, 0);
        }
    }
}