Only instantiate random seed once
Hello world,
I have a code spawning me some blocks in a grid:
var gridX = 16;
var gridY = 16;
var spacing = 10.0;
var xPosition = 0.0;
var yPosition = 0.0;
var blocks : GameObject[];
function Start () {
for (var y = 0; y < gridY; y++){
for (var x = 0; x < gridX; x++){
Instantiate(blocks[Random.Range(0, blocks.Length)], Vector3 (x+xPosition, y+yPosition, 0) * spacing, Quaternion.identity);
}
}
}
I assign the blocks in the Inspector and would like to restrict it from picking a certain prefab more than once. Is it possible to tell the instantiation to do that?
Cheers
Comment
Look up how to get a random list of numbers with no repeats. It's not really a Unity topic, but has been asked/answered here a few times.
Hi again, thanks for the answer.
Right, so I tried that and it works! However, it now spawns as many prefabs as I have in my list to choose from. Even though my grid is only 2x2, It'll still spawn all 10 I have in my list. Any idea what's wrong?
var gridX = 16;
var gridY = 16;
var spacing = 10.0;
var xPosition = 0.0;
var yPosition = 0.0;
var blocks : GameObject[];
function Start()
{
GenerateBlocks();
}
function GenerateBlocks()
{
//make a copy of the original one
//since we will be removing them from the array when we create them
var blocksCopy : GameObject[] = blocks;
for (var i = 0; i < blocks.Length; i++){
for (var y = 0; y < gridY; y++){
for (var x = 0; x < gridX; x++){
//pick a random index
var blocksNum : int = Random.Range(0, blocksCopy.Length-1);
yield WaitForSeconds(1);
Instantiate(blocksCopy[blocksNum], Vector3 (x+xPosition, y+yPosition, 0) * spacing, Quaternion.identity);
var blocksJS : Array = blocksCopy;
blocksJS.RemoveAt(blocksNum);
blocksCopy = blocksJS;
}
}
}
}