为了账号安全,请及时绑定邮箱和手机立即绑定

IENumerator 每次调用时都不会产生,并且随机范围不会在每次运行时重置

IENumerator 每次调用时都不会产生,并且随机范围不会在每次运行时重置

C#
qq_遁去的一_1 2022-12-24 10:26:22
我正在创建一个流星雨,它从游戏对象列表中选择一个随机的空游戏对象。我希望每 2.33f 实例化一颗流星。然后程序应从列表中选择一个新的随机生成区域并重复直到 smallWaveCounter 达到 0。此代码有效但它会不停地实例化流星,直到 smallWaveCounter 达到 0 并且实例化之间没有暂停。我的问题是:为什么 IENumerator 似乎只在第一次运行时产生?如何让它在每次触发时更改随机对象?[SerializeField]private List<GameObject> meteorSpawnSmall = new List<GameObject>(); private int smallCounter; private void Start(){    foreach(GameObject spawn in meteorSpawnSmall)//Counts objects in list    {        smallCounter++;    } }void Update(){ if (showerStart == true)    {                        StartCoroutine(SmallShower());        if(smallWaveCount <= 0)        {            showerStart = false;        }    }  }IEnumerator SmallShower(){    if (smallWaveCount > 0)    {        yield return new WaitForSeconds(smallWaveTimer);// smallWaveTimer = 2.33f        smallPickerNum1 = Random.Range(0, smallCounter - 1); // Needs to randomize each run        smallPickerNum2 = Random.Range(0, smallCounter - 1);        while (smallPickerNum2 == smallPickerNum1)        {            smallPickerNum2 = Random.Range(0, smallCounter - 1);        }        getSpawnZone1 = meteorSpawnSmall[smallPickerNum1];//Grabs the spawnzone from list        getSpawnZone2 = meteorSpawnSmall[smallPickerNum2];//Grabs the 2nd spawn zone from list        Instantiate(smallMeteor, getSpawnZone1.transform.position, Quaternion.identity);        Instantiate(smallMeteor, getSpawnZone2.transform.position, Quaternion.identity);        smallWaveCount--;//smallWaveCount starts at int 10    }}
查看完整描述

1 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

它确实每次都在等待,但你每帧都执行协程,所以你无法区分差异。改变你的代码有点像:


void Update()

{


 if (showerStart == true) {            

        showerStart = false; //to ensure that your coroutine called once

        StartCoroutine(SmallShower());

    }

}


IEnumerator SmallShower()

{

    while (smallWaveCount > 0)

    {

        yield return new WaitForSeconds(smallWaveTimer);// smallWaveTimer = 2.33f

        smallPickerNum1 = Random.Range(0, smallCounter - 1); // Needs to randomize each run

        smallPickerNum2 = Random.Range(0, smallCounter - 1);

        while (smallPickerNum2 == smallPickerNum1)

        {

            smallPickerNum2 = Random.Range(0, smallCounter - 1);

        }

        getSpawnZone1 = meteorSpawnSmall[smallPickerNum1];//Grabs the spawnzone from list

        getSpawnZone2 = meteorSpawnSmall[smallPickerNum2];//Grabs the 2nd spawn zone from list

        Instantiate(smallMeteor, getSpawnZone1.transform.position, Quaternion.identity);

        Instantiate(smallMeteor, getSpawnZone2.transform.position, Quaternion.identity);

        smallWaveCount--;//smallWaveCount starts at int 10

    }

}


查看完整回答
反对 回复 2022-12-24
  • 1 回答
  • 0 关注
  • 94 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信