Unity C# yield return new WaitForSeconds is stopping coroutine

I wanted to use a coroutine to make the player wait a little before shooting a new bullet but it never gets past the yield. Here's the code

 protected override void Start () {
     base.Start ();
     animator = GetComponent<Animator> ();
     score = GameManager.instance.playerScore;
     playerLives = GameManager.instance.playerLife;
 }
 void Update(){
     int horizontal = (int)Input.GetAxisRaw("Horizontal");
     AttemptMove (horizontal, 0);
     if (Input.GetKeyDown ("space")) {
         if(canShoot){
         Vector3 shootPosition = transform.position + new Vector3 (0, 0.5f, 0);
         Instantiate (bullet, shootPosition, Quaternion.identity);
         StartCoroutine(Shoot());
         }
     }
 }

 IEnumerator Shoot(){
     Debug.Log("Start");
     canShoot=false;
     yield return new WaitForSeconds (shootingTimeDelay);
     canShoot=true;
     Debug.Log("End");
 }

shootingTimeDelay is set to 1.1f. I am not destroying my gameObject anywhere and it works properly in other scripts in my project.

It never prints End. I don't get what is wrong

Answers


I would say don't use a coroutine for something like this.

Trying doing this and see if you get better restults

private float time = 0;

public float fireTime = 1.1f;

private void Update()
{
  time += Time.deltaTime;

  if(Input.GetKeyDown("space") && time >= fireTime)
  {
    Vector3 shootPosition = transform.position + new Vector3 (0, 0.5f, 0);
    Instantiate (bullet, shootPosition, Quaternion.identity);
    time = 0;
  }
}

Ok i found the bug. I had a method in its superclass that called StopAllCoroutines but for some reason i never tought of it until now. Changed that to StopCoroutine("name of my coroutine") and now it works perfect :)


Need Your Help