Do while loop crashing

I’m having a problem with my do while loop. I dont know if I’m missing something…simply put i have a code :


int numberOfItems;

void Start() {

numberOfItems = Random.Range(1,5);

}
void Update{

do{

StartCoroutine(“generateitem”);

}

while(numberOfItems > 0);

}

IEnumerator generateitem(){

yield return new WaitForSeconds(2f);

Instantiate(item, transform.position, Quaternion.identity);

numberOfItems -=1;

}


If I put it like that it crashes…if I shift decreament of numberOfItems and place it in the DO loop, it instantiate all the items at once without waiting for 2 seconds as in the Coroutine method.

The reason it crashes is because the numberOfItems variable changes only after the 2 second delay. Since the condition is to run the loop while it’s more than a zero, it ends up going on an infinite loop until those two seconds pass which probably doesn’t happen due to the editor crashing.

Here’s an updated version of your solution:

private int numberOfItems;

private void Start()
{
    numberOfItems = Random.Range(1, 5);
    StartCoroutine(GenerateAllItems());
}

private IEnumerator GenerateAllItems()
{
    do
    {
        yield return new WaitForSeconds(2f);
        GenerateItem();
    }
    while (numberOfItems > 0);
}

private void GenerateItem()
{
    Instantiate(item, transform.position, Quaternion.identity);
    numberOfItems -= 1;
}