一段时间后如何停止产生敌人?基本想法是我的敌人会随机产生,我需要某种方法来阻止他们在一定时间后产生。
下面是我的代码:
[SerializeField] float minSpawnDelay = 1f;
[SerializeField] float maxSpawnDelay = 5f;
[SerializeField] Attacker[] attackerPrefabArray;
[SerializeField] float spawnerDelay = 1f;
bool spawn = true;
IEnumerator Start()
{
yield return new WaitForSeconds(spawnerDelay);
while (spawn)
{
yield return new WaitForSeconds(Random.Range(minSpawnDelay, maxSpawnDelay));
SpawnAttacker();
}
}
public void StopSpawning()
{
spawn = false;
}
private void SpawnAttacker()
{
var attackerIndex = Random.Range(0, attackerPrefabArray.Length);
Spawn(attackerPrefabArray[attackerIndex]);
}
private void Spawn(Attacker myAttacker)
{
Attacker newAttacker = Instantiate
(myAttacker, transform.position, transform.rotation)
as Attacker;
newAttacker.transform.parent = transform;
}
答案 0 :(得分:0)
您可以为此使用计时器:
// Enemies will spawn for 5 seconds.
private float spawnTimer = 5f;
private void Update()
{
if (spawnTimer > 0)
{
spawnTimer -= Time.deltaTime;
if (spawnTimer <= 0)
{
StopSpawning();
}
}
}
答案 1 :(得分:0)
在的IEnumerator总是用于该目的。在特定时间间隔后触发事件时,将使用WaitForSeconds(timespan)。只需使用下面的代码,并在“ yield return new WaitForSeconds(5);”之后编写您的desried函数即可。它将触发或运行您想要的功能。
IEnumerator Example()
{
print(Time.time);
yield return new WaitForSeconds(5);
StopSpawning(enter code here); //your function
print(Time.time);
}