'Trying to end a coroutine after one or two seconds of it running

I'm making a game in Unity, where you have to pick up trash and take it to the correct bin, and I've created a code that randomly spawns the trash. It works fine, but it's spawning infinitely, yet I only want a certain amount to spawn.

I would like the coroutine to run for about 1 or 2 seconds for somewhere around 10 items to spawn in total. Any ideas?

    void Start()
{
    StartCoroutine(TrashSpawnn());
}

IEnumerator TrashSpawnn()
{
    while(true)
    {
        var wanted = Random.Range(minTras, maxTras);
        var position = new Vector3(wanted, transform.position.y);
        GameObject gameObject = Instantiate(trashPrefab[Random.Range(0, trashPrefab.Length)],
        position, Quaternion.identity);
        yield return new WaitForSeconds(secondSpawn);
    }    
}

}



Solution 1:[1]

Well, you are using an infinite loop.

Use a for loop instead to run your spawning code 10 times:

for (int i = 0; i < 10; i++)
{
    var wanted = Random.Range(minTras, maxTras);
    var position = new Vector3(wanted, transform.position.y);
    GameObject gameObject = Instantiate(trashPrefab[Random.Range(0, trashPrefab.Length)],
    position, Quaternion.identity);
    yield return new WaitForSeconds(secondSpawn);
} 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ruzihm