简体   繁体   English

在运行一两秒后尝试结束协程

[英]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.我正在 Unity 中制作游戏,您必须在其中捡起垃圾并将其带到正确的垃圾箱,并且我创建了一个随机产生垃圾的代码。 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.我希望协程运行大约 1 或 2 秒,总共生成大约 10 个项目。 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);
    }    
}

} }

Well, you are using an infinite loop.嗯,你正在使用一个无限循环。

Use a for loop instead to run your spawning code 10 times:使用for循环代替运行生成代码 10 次:

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);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM