Unity Wait for second after a renderer

I have an renderer that’s by default of. When I push a button it turns on. But I only want it on for a few seconds.

Code:

using UnityEngine;
using System.Collections;

public class Boost : MonoBehaviour {

// Update is called once per frame
void Start () {
	GetComponent<Renderer>().enabled = false;
}

void Update () {
	if (Input.GetKey (KeyCode.Joystick1Button1))
		GetComponent<Renderer>().enabled = true; //wait for 5 seconds
	}

}

Can anybody help?

This can be achieved two ways:

1:
Coroutines

Coroutines allow you to use WaitForSeconds, which only returns after the waited period in your code. You can modify your script by adding this after your comment to wait for 5 seconds:

StartCoroutine(WaitThenDisable());

Then the following function:

IENumerator WaitThenDisable() {

    yield return new WaitForSeconds(5f);

    GetComponent<Renderer>().enaled = false;
}

While Coroutines may be more efficient, new things scare people sometimes. You can achieve the same result within the update function.

2:

Using the update function, you can add this to your script:

public float delay = 5f;
public bool alreadyDisabled;

And the following to your Update function:

void Update() {

    if(delay <= 0 && !alreadyDisabled) {
        GetComponent<Renderer>().enabled = false;
        
        alreadyDisabled = true;
    }
    else
    delay -= Time.deltaTime;


}

Essentially, once the float reaches 0, it will disable the Renderer. The float gets closer to 0 by subtracting the time (in seconds) from the previous frame.

I would recommend the Coroutine version, but both should work.
Tell me if it works, or if there’s problems. Good luck!

bool rendererOn = false;

 void Start () {
     GetComponent<Renderer>().enabled = false;
 }
 
 void Update () {
     if (Input.GetKey (KeyCode.Joystick1Button1) && rendererOn == false)
      StartCoroutine("WorkRenderer");
     }

IEnumerator WorkRenderer(){
   GetComponent<Renderer>().enabled = true;
     rendererOn = true;
     yield return new WaitForSeconds(5.0f);
   GetComponent<Renderer>().enabled = false;
    rendererOn = false;
 }

}