我試圖讓協程每 0.2 秒一次生成一個物件,但是當我運行協程時,它一次生成多個物件,沒有任何延遲。我怎樣才能解決這個問題并達到預期的效果?
我的代碼:
if (shotExtender > 0)
{
StartCoroutine("Timer");
}
else
{
StopCoroutine("Timer");
}
協程
IEnumerator Timer()
{
while (objCounter < 3)//it should spawn only 3 objects
{
yield return new WaitForSeconds(0.2f);
GameObject bullet = PhotonNetwork.Instantiate(bulletPref.name, bulletPosition, Quaternion.identity);
objCounter ;
Debug.Log("objCounter: " objCounter " maxBullets: " maxBullets);
}
objCounter = 0;
shotExtender = 0;//This stops the coroutine
}
uj5u.com熱心網友回復:
嘗試在協程之外取出物件計數器重置器和鏡頭擴展器重置器。我相信 if 陳述句被多次訪問,在第一個協程完成之前生成了多個協程!
if (shotExtender > 0)
{
StartCoroutine("Timer");
objCounter = 0;
shotExtender = 0;//This stops the coroutine
}
uj5u.com熱心網友回復:
如果此代碼在更新中運行
if (shotExtender > 0)
{
StartCoroutine("Timer");
}
else
{
StopCoroutine("Timer");
}
您必須在開始這樣的程序之前完成條件
if (shotExtender > 0)
{
shotExtender = 0;
StartCoroutine("Timer");
}
else
{
StopCoroutine("Timer");
}
uj5u.com熱心網友回復:
上面的答案讓我走上了正軌。我做了以下所有事情并且它起作用了:
if (shotExtender > 0)
{
StartCoroutine("Timer");
}
.
IEnumerator Timer()
{
while (objCounter < maxBullets)
{
yield return new WaitForSeconds(0.2f);
GameObject bullet = PhotonNetwork.Instantiate(bulletPref.name, bulletPosition, Quaternion.identity);
shotCounter ;
Debug.Log("corutine works. objCounter: " objCounter " maxBullets: " maxBullets);
}
StopCoroutine("ShotTimer");
objCounter = 0;shotExtender = 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/428503.html
上一篇:是否可以使用async/await在Unity中加載資源?
下一篇:當int變數超過10位時
