[英]Unity freeze when play button is pressed
我正在通過 udemy 課程學習 Unity。
現在,當我點擊播放按鈕時,我被困在統一屏幕凍結的地方。 它發生在隨機定位的敵人的生成管理器中,並且敵人的IEnumerator
可以完美地工作,但是一旦我為通電添加相同的內容並點擊播放按鈕,它就會凍結。
當我在生成管理器中注釋掉 powerup 部分並重新啟動 unity 時,它可以完美運行。
我應該怎么做才能讓我的加電生成器工作?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
[SerializeField]
private GameObject _enemyShipPrefab;
[SerializeField]
private GameObject[] powerup;
// Start is called before the first frame update
void Start()
{
StartCoroutine(EnemySpawnRoutine());
StartCoroutine(PowerupSpawnRoutine());
}
public IEnumerator EnemySpawnRoutine()
{
while(true)
{
float enemyPositionX = Random.Range(-8.34f, 8.34f);
Instantiate(_enemyShipPrefab, new Vector3(enemyPositionX, 6.39f, 0), Quaternion.identity);
yield return new WaitForSeconds(5.0f);
}
}
public IEnumerator PowerupSpawnRoutine()
{
while(true)
{
// float powerupPositionX = Random.Range(-8.622f, 8.622f);
int randomPowerup = Random.Range(0, 3);
Instantiate(powerup[randomPowerup], new Vector3(Random.Range(-8.622f, 8.622f), 4.5f, 0), Quaternion.identity);
}
}
}
在您的PowerupSpawnRoutine
中, while(true)
始終會作為無限循環運行。 你不會yield
它里面的任何地方。
您還應該在PowerupSpawnRoutine
中添加延遲。
public IEnumerator PowerupSpawnRoutine()
{
while(true)
{
// float powerupPositionX = Random.Range(-8.622f, 8.622f);
int randomPowerup = Random.Range(0, 3);
Instantiate(powerup[randomPowerup], new Vector3(Random.Range(-8.622f, 8.622f), 4.5f, 0), Quaternion.identity);
// this e.g. will spawn powerup after every 5 seconds.
yield return new WaitForSeconds(5.0f);
}
}
正如Muhammad Farhan Aqeel已經提到的那樣,您在PowerupSpawnRoutine
的while(true)
循環內的任何地方都沒有yield
。
但是,作為這里的完整替代方案,您也可以在您的用例中使用InvokeRepeating
,而不是使用 Coroutines:
[SerializeField] private float enemySpawnDelay = 5f;
[SerializeField] private float powerupSpawnDelay = 5f;
// Start is called before the first frame update
void Start()
{
// The first parameter is the initial delay so 0 makes the first call
// immediately.
// The second parameter is the repeating delay
InvokeRepeating(nameof(EnemySpawnRoutine), 0f, enemySpawnDelay);
InvokeRepeating(nameof(PowerupSpawnRoutine), 0f, powerupSpawnDelay);
}
private void EnemySpawnRoutine()
{
float enemyPositionX = Random.Range(-8.34f, 8.34f);
Instantiate(_enemyShipPrefab, new Vector3(enemyPositionX, 6.39f, 0), Quaternion.identity);
}
private void PowerupSpawnRoutine()
{
// when getting random indices use the actual length of the array to be more
// flexible and secure against errors
int randomPowerup = Random.Range(0, powerup.Length);
Instantiate(powerup[randomPowerup], new Vector3(Random.Range(-8.622f, 8.622f), 4.5f, 0), Quaternion.identity);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.