产生敌人Unity3D的波浪

时间:2014-12-08 23:17:47

标签: c# unity3d

我正在开发一种我想要产生一波敌人的游戏。在每一波敌人中,我从不同的生成点产生。例如,我有6个Spawn点,从第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);
     }
 }
 }

1 个答案:

答案 0 :(得分:0)

由于spawnPointIndex是在循环中拾取的,因此它会为wave中的每个危险点选择一个新的随机生成点。如果你想让它使用相同的spawnpoint,那么选择在hazard环境之外的spawnPointIndex,但是在wave内部(true)循环:

 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