- Home /
Spawn random prefabs at multiple locations
Hello, I am trying to randomly generate a city. I have 20 points in the world and with one script I'd like to randomly generate a building from a list of 10 at each one of those points. I am stuck and don't know where to go with the code. I have a code but all it is able to do is randomly spawn a building at one location (the location which has this code) I need it to be able to randomly spawn a building (different buildings) at 20 different locations. Any assistance helps! Thank you! Code:
//The list of the 20 spawn points
public var Block : Transform [];
public var ObjectSpawned : GameObject;
//The list of the 10 buildings to randomly spawn at each spawn point
public var ObjecttoSpawn1 : GameObject;
public var ObjecttoSpawn2 : GameObject;
public var ObjecttoSpawn3 : GameObject;
public var ObjecttoSpawn4 : GameObject;
public var ObjecttoSpawn5 : GameObject;
public var ObjecttoSpawn6 : GameObject;
public var ObjecttoSpawn7 : GameObject;
public var ObjecttoSpawn8 : GameObject;
public var ObjecttoSpawn9 : GameObject;
public var ObjecttoSpawn10 : GameObject;
var TimeToSpawn : int;
var RandomNumber : int;
RandomNumber = Random.Range(1.0, 5.0);
TimeToSpawn = Random.Range(1.0,10.0);
function Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
{
Invoke ("spawnObject", TimeToSpawn); //Spawn an object after time and once space is pressed
}
}
function Start ()
{
//These designate an object to a number when the random number is picked
//I would like the random number to reshuffle so that there is a random chance for each building to be spawned at each spawn point
if (RandomNumber == 1)
{
ObjectSpawned = ObjecttoSpawn1;
}
if (RandomNumber == 2)
{
ObjectSpawned = ObjecttoSpawn2;
}
if (RandomNumber == 3)
{
ObjectSpawned = ObjecttoSpawn3;
}
if (RandomNumber == 4)
{
ObjectSpawned = ObjecttoSpawn4;
}
if (RandomNumber == 5)
{
ObjectSpawned = ObjecttoSpawn5;
}
if (RandomNumber == 6)
{
ObjectSpawned = ObjecttoSpawn6;
}
if (RandomNumber == 7)
{
ObjectSpawned = ObjecttoSpawn7;
}
if (RandomNumber == 8)
{
ObjectSpawned = ObjecttoSpawn8;
}
if (RandomNumber == 9)
{
ObjectSpawned = ObjecttoSpawn9;
}
if (RandomNumber == 10)
{
ObjectSpawned = ObjecttoSpawn10;
}
}//Start Function end bracket
function spawnObject()
{
//Spawn Object at curret location
//I do not know how to code it so that it spawns 20 different times
Instantiate (ObjectSpawned, transform.position, transform.rotation);
}
Answer by Fanttum · Mar 15, 2015 at 03:03 AM
Sounds like you need a For Loop somewhere in there.
Not quite the same thing, but this tutorial might also be helpful.
Your answer
![](https://koobas.hobune.stream/wayback/20220613190154im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
spawning random objects at 2 defined points 1 Answer
Random element from the list 1 Answer
Problem with random spawning and coroutine 1 Answer
Random select from array and spawn 1 Answer