Skip to main content
Removed from Network Questions by Vaillancourt

I'm new to Unity. I was learning coroutines and I wrote this. enter image description here

private void Fire()
{
    if(Input.GetButtonDown("Fire1"))
    {
        StartCoroutine(FireContinuously());
    }
    if(Input.GetButtonUp("Fire1"))
    {
        StopAllCoroutines();
    }
}

IEnumerator FireContinuously()
{
    while(true)
    {
        GameObject laser = Instantiate(LaserPrefab, transform.position, Quaternion.identity) as GameObject;
        laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 10f);
        yield return new WaitForSeconds(firetime);
    }
}

When the button is pressed the coroutine is called and it enters the 'while' loop. When I leave the button it stops the coroutine. Shouldn't it get stuck in the 'while' loop as it is an infinite loop ? Why?

I'm new to Unity. I was learning coroutines and I wrote this. enter image description here

When the button is pressed the coroutine is called and it enters the 'while' loop. When I leave the button it stops the coroutine. Shouldn't it get stuck in the 'while' loop as it is an infinite loop ? Why?

I'm new to Unity. I was learning coroutines and I wrote this.

private void Fire()
{
    if(Input.GetButtonDown("Fire1"))
    {
        StartCoroutine(FireContinuously());
    }
    if(Input.GetButtonUp("Fire1"))
    {
        StopAllCoroutines();
    }
}

IEnumerator FireContinuously()
{
    while(true)
    {
        GameObject laser = Instantiate(LaserPrefab, transform.position, Quaternion.identity) as GameObject;
        laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 10f);
        yield return new WaitForSeconds(firetime);
    }
}

When the button is pressed the coroutine is called and it enters the 'while' loop. When I leave the button it stops the coroutine. Shouldn't it get stuck in the 'while' loop as it is an infinite loop ? Why?

Tweeted twitter.com/StackGameDev/status/1158890607210848263
Became Hot Network Question
Replace unityscript tag with C#, the language used in the code sample.
Link
Source Link

Why am I not getting stuck in the loop

I'm new to Unity. I was learning coroutines and I wrote this. enter image description here

When the button is pressed the coroutine is called and it enters the 'while' loop. When I leave the button it stops the coroutine. Shouldn't it get stuck in the 'while' loop as it is an infinite loop ? Why?