- Home /
Instantiate prefab at certain positions
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?
Answer by jenci1990 · Jan 31, 2015 at 04:45 PM
void SpawnEnemy() {
List<Vector3> 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);
}
}
Answer by Andreapigna · Jan 31, 2015 at 02:16 PM
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)
i'm italian too can you give me some way to chat? I need a little help if you want to
yeah, you could contact me on skype at andrea.signorelli13 (i'm not on very much though)
Answer by DESIMA · Jan 31, 2015 at 07:27 PM
yeah so it get positioned on top of each other because you are getting random numbers that could be the same ones allready taken.
to get unique numbers one way could be to create a list of random numbers where all are unique and then use that list.
you can use a set whish is called HashSet in C#
http://stackoverflow.com/questions/5157787/collection-that-allows-only-unique-items-in-net
so make your random numbers and input the output into the hashset. Then iterate through that set.
you can also just put your random numbers in a list and then for every new number check your list to see if the number allready is there.
However if you are dealing with many numbers, over 1000 of length then it would take more time using that simple approach.