- Home /
How do I randomize the order of spawn points without repeats?
I have 30 spawn points and I need the player to visit all of them before the game is over. When the player hits one of the arrow keys, I want them to be transported to the next spawn point (it may be easier to make each of the spawn points their own level, I'm not sure). Once the player visits a spawn point, I do not want them to be able to return to that point. In other words, on the first spawn there would be 30 possibilities, on the 2nd there would be 29, etc.
I was thinking of doing this with an array and having the index destroy or delete itself after it has been visited, but if there is a better way to do it, I'm all ears.
I'm new to coding so any and all help is really really REALLY appreciated! Thank you!
i was about to suggest using an array of GameObjects when i read the line that said you were going to do that. Definitely what i would do, good thinking.
although there may be a better way to do it, but not any that i can think of.
Answer by Owen-Reynolds · Oct 22, 2013 at 09:15 PM
Random without repeats is sort of a special case. the best way to do it is to shuffle them ahead of time (like a deck of cards,) then visit them all in order (like once you shuffle some cards, you don't need to pick randomly -- can just deal from the top.)
A simple array shuffle (assumes that A is an array of Empties, which are Transforms):
for(int i=0;i<A.Length;i++) {
int i2 = Random.Range(0, A.Length); // NOTE: 0 to len-1
// swap i and i2. OK if they are the same:
Transform temp = A[i]; A[i]=A[i2]; A[i2]=temp;
}
It seems like it might swap an item into the same place, or swap an item back to where it was. It can, but with the correct 1 in 30 chance.
The alternative, which seems more obvious, has you rolling, say, 0 to 24 and counting, skipping unused ones. Giant pain, and risks infinite loops if the count gets off.
This looks great! I'll try it out and let you know how it goes. Thanks!
Your answer
Follow this Question
Related Questions
Spawn Multiple Monsters 1 Answer
WaveSpawn Script. Help 0 Answers
Scripts are being disabled during game play 0 Answers
Unable To spawn Multiple Objects 1 Answer
A respawn script for enemies. 1 Answer