我已经在我的 Unity 2D 项目的主要 Gameplay.cs 脚本中处理这部分代码很长一段时间了,无论我以哪种方式更改它并改变它,它要么导致 Unity 锁定在 Play 上,要么,经过一些调整,会立即从 Wave 0 转到 Wave 9。这是我最初的尝试,它导致 Unity 在 Play 上冻结。我不明白为什么会发生这种情况,并想了解我的逻辑哪里出了问题。
我正在努力实现以下目标:
- 在 Play 上,游戏等待 startWait 秒。
- 在 startWait 之后,游戏进入 SpawnWaves() 方法并在每个波之间等待 waveWait 秒,并在每个波期间将波计数增加一。
- 每一波都会产生zombieCount 数量的敌人并在每个僵尸产生之间等待 spawnWait 秒。
private float startWait = 3f; //Amount of time to wait before first wave
private float waveWait = 2f; //Amount of time to wait between spawning each wave
private float spawnWait = 0.5f; //Amount of time to wait between spawning each enemy
private float startTimer = 0f; //Keep track of time that has elapsed since game launch
private float waveTimer = 0f; //Keep track of time that has elapsed since last wave
private float spawnTimer = 0f; //Keep track of time that has elapsed since last spawn
private List<GameObject> zombies = new List<GameObject>();
[SerializeField]
private Transform spawnPoints; //The parent object containing all of the spawn point objects
void Start()
{
deathUI.SetActive(false);
//Set the default number of zombies to spawn per wave
zombieCount = 5;
PopulateZombies();
}
void Update()
{
startTimer += Time.deltaTime;
if (startTimer >= startWait)
{
waveTimer += Time.deltaTime;
spawnTimer += Time.deltaTime;
SpawnWaves();
}
//When the player dies "pause" the game and bring up the Death screen
if (Player.isDead == true)
{
Time.timeScale = 0;
deathUI.SetActive(true);
}
}
void SpawnWaves()
{
while (!Player.isDead && ScoreCntl.wave < 9)
{
if (waveTimer >= waveWait)
{
IncrementWave();
for (int i = 0; i < zombieCount; i++)
{
if (spawnTimer >= spawnWait)
{
Vector3 spawnPosition = spawnPoints.GetChild(Random.Range(0, spawnPoints.childCount)).position;
Quaternion spawnRotation = Quaternion.identity;
GameObject created = Instantiate(zombies[0], spawnPosition, spawnRotation);
TransformCreated(created);
spawnTimer = 0f;
}
}
waveTimer = 0f;
}
}
}
我是初学者,并且了解我的代码可能不遵循最佳实践。我也有一个使用协程和收益回报的工作敌人产卵器,但想让这个版本的我的敌人产卵工作。