Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Iterator never returns warning with coroutines

Discussion in 'Scripting' started by SmushyTacoDevelopment, Apr 4, 2020.

  1. SmushyTacoDevelopment

    SmushyTacoDevelopment

    Joined:
    Mar 30, 2020
    Posts:
    8
    So I have the code below using a coroutine to fire a laser for a space shooter game continuously by hold pressing the fire key and I have it stopping the coroutine when the player stops pressing on the fire key. The code works perfectly fine but I get this one warning that's bugging me so I was wondering if anybody knew anyway to get rid of the warning.

    Code (CSharp):
    1.     private IEnumerator FireLaserContinuously() {
    2.         while (true) {
    3.             var laser = Instantiate(laserPrefab, transform.position, Quaternion.identity);
    4.             laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, laserSpeed);
    5.             yield return new WaitForSeconds(laserFiringSpeed);
    6.         }
    7.     } // Iterator never returns
    8.     private void FireLaser() {
    9.         if (Input.GetButtonDown("Fire1")) {
    10.             laserFiringCoroutine = StartCoroutine(FireLaserContinuously());
    11.         } else if (Input.GetButtonUp("Fire1")) {
    12.             StopCoroutine(laserFiringCoroutine);
    13.         }
    14.     }
    15.     private void Update() {
    16.         FireLaser();
    17.     }
    If you look above you'll see I put a comment where I see the warning in my IDE. I hope all this information helps!
     
    Last edited: Apr 5, 2020
  2. SmushyTacoDevelopment

    SmushyTacoDevelopment

    Joined:
    Mar 30, 2020
    Posts:
    8
    Figured it out:

    Code (CSharp):
    1. private const float LaserFiringCooldown = 0.1f;
    2. private bool _canShootLaser = true;
    3. private IEnumerator FireLaserCooldown() {
    4.         yield return new WaitForSeconds(LaserFiringCooldown);
    5.         _canShootLaser = true;
    6.     }
    7.     private void FireLaser() {
    8.         if (!Input.GetButton("Fire1") || !_canShootLaser) return;
    9.         var laser = Instantiate(laserPrefab, transform.position, Quaternion.identity);
    10.         laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, laserSpeed);
    11.         _canShootLaser = false;
    12.         StartCoroutine(FireLaserCooldown());
    13.     }
    14.     private void Update() {
    15.         FireLaser();
    16.     }
     
  3. CNC_Sai

    CNC_Sai

    Joined:
    May 15, 2018
    Posts:
    4
    Was it a matter of reordering the ' yield return' ?