你好,我有一个敌人产卵系统,它的工作正常。然而敌人在同一点重叠,因为我使用random.range,我在地图上有4个点,我希望每个敌人随机选择一个点。因此,我希望在产生敌人之后,另一个敌人只能获得3个选择,而不是4个。
这是我的代码:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Spawn : MonoBehaviour {
// The enemy prefab to be spawned.
public GameObject[] enemy;
//public Transform[] spawnPoints;
public List<Transform> spawnPoints = new List<Transform>();
private float timer = 3;
int index = 0;
List <GameObject> EnemiesList = new List<GameObject>();
private int m_enemyCount = 4;
// Update is called once per frame
void Update () {
if (timer >0)
{
timer -= Time.deltaTime;
}
if (timer <= 0 )
{
if ( EnemiesList.Count == 0 )
{
Spawner();
timer = 5;
}
}
}
void Spawner ()
{
// Create an instance of the enemy prefab at the randomly selected spawn point's position.
//Create the enemies at a random transform
for (int i = 0; i<m_enemyCount;i++)
{
int spawnPointIndex = Random.Range (0, spawnPoints.Count);
Transform pos = spawnPoints[spawnPointIndex];
GameObject InstanceEnemies= Instantiate ( enemy[index] , spawnPoints[spawnPointIndex].position , Quaternion.identity) as GameObject;
// Create enemies and add them to our list.
EnemiesList.Add(InstanceEnemies);
}
}
答案 0 :(得分:2)
处理此问题的一种简单方法是在Spawner()
方法中创建一个生成点的本地列表,这样您就可以跟踪已经使用过的生成点。例如:
void Spawner ()
{
//create a local list of spawn points
List<Transform> availablePoints = new List<Transform>(spawnPoints);
// Create an instance of the enemy prefab at the randomly selected spawn point's position.
//Create the enemies at a random transform
for (int i = 0; i<m_enemyCount;i++)
{
//use local availableSpawnPoints instead of your global spawnPoints to generate spawn index
int spawnPointIndex = Random.Range (0, availableSpawnPoints.Count);
Transform pos = spawnPoints[spawnPointIndex];
GameObject InstanceEnemies= Instantiate ( enemy[index] , avaialableSpawnPoints[spawnPointIndex].position , Quaternion.identity) as GameObject;
// Create enemies and add them to our list.
EnemiesList.Add(InstanceEnemies);
//remove the used spawnpoint
availableSpawnPoints.RemoveAt(spawnPointIndex);
}
}
此解决方案可确保您下次调用Spawner()
方法时,您的全局生成点列表将保持不变。
答案 1 :(得分:0)
从for循环结尾处的列表spawnPoints
中删除已经生成的spawnpoints,如下所示:
spawnPoints.RemoveAt(spawnPointIndex);
您可能希望在for循环之前创建该列表的副本,但要保持原始格式。