生成一波又一波的敌人 Unity3D
本文关键字:敌人 Unity3D | 更新日期: 2023-09-27 18:33:32
我正在开发一款游戏,我想在其中生成一波又一波的敌人。在每一波敌人中,我都会从不同的出生点生成。例如,我有 6 个重生点,第一波敌人从第 4 个点生成,第二波从第 1 个点生成,依此类推。
我写了一个代码,让我生成一波又一波的敌人,但我的问题是它从第一波敌人的所有 6 个出生点生成一波又一波的敌人。
当我点击游戏时,我有来自 6 个重生点的敌人波浪,而不是每波来自一个重生点。
using UnityEngine;
using System.Collections;
public class Waves : MonoBehaviour
{
public GameObject Enemy = null;
public int hazardCount = 3;
public float spawnWait=0.5f;
public float startWait=1;
public float waveWait=4;
public Transform[] spawnPoints;
void Start ()
{
StartCoroutine(SpawnWaves ());
}
IEnumerator SpawnWaves ()
{
yield return new WaitForSeconds (startWait);
while (true)
{
for (int i = 0; i < hazardCount; i++)
{
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
Instantiate (Enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
yield return new WaitForSeconds (spawnWait);
}
yield return new WaitForSeconds (waveWait);
}
}
}
由于 spawnPointIndex 是在循环中选取的,因此它会为波中的每个危险选取一个新的随机生成点。如果您希望它使用相同的生成点,请在危险循环之外但在波浪 while(true) 循环内选择 spawnPointIndex:
IEnumerator SpawnWaves ()
{
yield return new WaitForSeconds (startWait);
while (true)
{
// Only pick a new spawn point once per wave
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
for (int i = 0; i < hazardCount; i++)
{
// here would pick a new spawn point for each new enemy
Instantiate (Enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
yield return new WaitForSeconds (spawnWait);
}
yield return new WaitForSeconds (waveWait);
}
}
还要考虑从对象池中拉出敌人,而不是每次都实例化新的敌人。它会更有效率。见 http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling