Hello,
I searched around and found different pieces of code that even though separately cover all parts of my problem, when put together are not working…
Here is what I need to do :
- I have 14 spawn points located on my terrain.
- I have 14 game objects to spawn.
- What I need is to spawn one object (chosen at random, let’s say Number3 from gameobject list) at spawn point Nr1 (spawn points can be iterated based on their number)
- Next iteration is to choose again a new object from the updated gameobject list(the gameobject list, minus Number3 which was previously spawned) and spawn it at spawn point Nr2
- Iterations continue until all objects are uniquely spawned on all the spawn points.
I need this for my game world map, where the objects will represent loading triggers for the respective scenes.
Help is very much appreciated as I am still a newbie in scripting.
Thank you.
One way to do it is to shuffle the spawn point array, then you can do something like this:
for( int i = 0; i < spawnPoints.length; ++i ) {
/*Spawn gameObjectArray <em>at spawnPoints_;*/_</em>
}
To do a shuffle, you can go for a [Fisher–Yates shuffle][1]:
Transform [] myArray = …;
int i = myArray.length;
while( --i >= 0 ) {
int randIndex = Random.Range( 0, myArray.length );
//Swap i with a random index
Transform temp = myArray*;*
myArray = myArray[randIndex];
myArray[randIndex] = temp;
}
----------
If you are using a collection to store the spawn points, then you can go for this:
List spawnPoints = …;
//You can use either collections or array to store the spawned object, it doesn’t matter
GameObject[] spawnThis = …;
…
for( int i = 0; i < spawnThis.Length; ++i ) {
int randIndex = Random.Range( 0, spawnPoints.Count );
Transform sp = spawnPoints[randIndex];
spawnPoints.RemoveAt( randIndex );
/Spawn spawnThis _at sp/
}_
[1]: Fisher–Yates shuffle - Wikipedia
for( int i = 0; i < spawnThis.Length; ++i )
{
Debug.Log (sizeOfList);
int randIndex = Random.Range( 0, sizeOfList );
Transform sp = spawnPoints[randIndex];
spawnPoints.RemoveAt( randIndex );
}
You are changing the values inside your list during the loop, so that your sizeOfList != spawnPoints.Count. If your Random,Range then tries to get the spawnPoint from 0 to sizeOfList it may get an index of your list no longer existing ( sizeOfList == 14, spawnPoints.Count == 13 ) which ends up in a null reference exception.
You should not Remove the spawnPoint inside the loop OR you should simply reduce your sizeOfList after RemoveAt by 1 as well.
Greetz