Hello everyone,
I have a small problem with a script, I would like to instantiate objects at certain positions, it all works, but I have the problem that sometimes I instantiates the objects on top of each other.
This is the script that I made
public List<GameObject> Sprites;
public int n;
public List<Vector3> SpawnPosition;
void Start ()
{
SpawnEnemy ();
}
void Update ()
{
}
void SpawnEnemy ()
{
for (int i = 0; i < n; i++)
{
Vector3 spawnPosition = SpawnPosition[Random.Range (0,SpawnPosition.Count)];
Instantiate (Sprites[Random.Range (0,Sprites.Count)] , spawnPosition, transform.rotation);
}
}
How can I do to eliminate positions that have already been chosen randomly?
I’m totally wrong and I have to do it another way?
You could create a array where you put the various Vector3 you randomly create. Then, when another spawnposition is selected, you compare it with all the elements in the array. if it already exists, it’ll create another one randomly (try using a for cycle to compare all the vectors)
void SpawnEnemy() {
List positionList = SpawnPosition;
for (int i = 0; i < n; i++) {
if (positionList.Count == 0) return;
int index = Random.Range(0, positionList.Count);
Vector3 spawnPosition = positionList[index];
Instantiate(Sprites[Random.Range(0, Sprites.Count)], spawnPosition, transform.rotation);
//Remove the position from list what was used
positionList.RemoveAt(index);
}
}