WaitForSeconds() Is not working.

In my code whenever I click a prefab is instantiated (shooting). But i want a cool down town timer so i added the WaitForSeconds method but its not working. What is the problem. Here is my code:

	void Update () {
		if(Input.GetMouseButton(0))
		{
		StartCoroutine( Shoot());
		}
	}

	IEnumerator Shoot()
	{
		Instantiate(Laser, Launcher.transform.position, Launcher.transform.rotation);
		yield return new WaitForSeconds(5.0f);
	}

Coroutines are not used for that, they don’t prevent a piece of code from being called, you’re starting a new Shoot coroutine on every Update where the condition is true (the mouse button being down).

A coroutine is just a method like every other, but it can stop at some point and continue from there later. In your case your coroutine is instantiating the laser, then stops for 5 seconds and then it finishes.

I’d do it without a coroutine, just store the time of the previous shoot and check if it passed enough time in the if condition. Something like this:

public float lastShootAt;
 
void Update () {
    if(Input.GetMouseButton(0) && Time.time >= lastShootAt + 5f)
    {
        lastShootAt = Time.time;
        Instantiate(Laser, Launcher.transform.position, Launcher.transform.rotation);
    }
}

Here, Try this:

public bool canShoot = true;
void Update () {
  if(Input.GetMouseButton(0) && canShoot) {
    StartCoroutine( Shoot());
  }

 IEnumerator Shoot() {
   canShoot = false;
   Instantiate(Laser, Launcher.transform.position, Launcher.transform.rotation);
   yield return new WaitForSeconds(5.0f);
   canShoot = true;
 }
}

have you tried adding a boolean to activate and deactivate the cooldown either end of the IEnumeration to prevent it being called again? just adding a WaitForSeconds will not prevent the Coroutine from being called again…

Try this…

public bool _cooldown = false;

void Update () {
         if(Input.GetMouseButton(0) && _cooldown == false)
         {
         StartCoroutine( Shoot());
         }
     }
 
     IEnumerator Shoot()
     {
         _cooldown = true;
         Instantiate(Laser, Launcher.transform.position, Launcher.transform.rotation);
         yield return new WaitForSeconds(5.0f);
         _cooldown = false;
     }

try removing the 0 in 5.0f.

I don’t think you need to say StartCoroutine. Try just saying

Shoot();

instead of

StartCoroutine(Shoot());

Also try saying just

yield WaitForSeconds(5.0f);

if that doesn’t work, I would switch to javascript. I switched from c# to javascript and its much faster.

function Update () {

     if(Input.GetMouseButton(0))  

     {  

     Shoot();  

     }  

 }  



 function Shoot()  

 {  

     Instantiate(Laser, Launcher.transform.position, Launcher.transform.rotation);  

     yield WaitForSeconds(5);  

 }