- Home /
Random Spawning of Objects at Random Locations
Hello, I have thrown together a random spawning script, however i would like it to be a bit more complicated. At the moment i have a spawn point being chosen at random however, that the chose spawn point will only ever spawn the same object. Here is what i have so far:
var timer : float = 0.0;
var spawning : boolean = false;
var meteor1 : Rigidbody;
var meteor2: Rigidbody;
var meteor3 : Rigidbody;
var spawn1 : Transform;
var spawn2 : Transform;
var spawn3 : Transform;
function Update () {
if(!spawning){
timer += Time.deltaTime;
}
if(timer >= 1.5){
Spawn();
}
}
function Spawn(){
spawning = true;
timer = 0;
var randomPick : int = Mathf.Abs(Random.Range(1,4));
var location : Transform;
var whichObj : Rigidbody;
if(randomPick == 1){
location = spawn1;
whichObj = meteor1;
Debug.Log("Chose pos 1");
}
else if(randomPick == 2){
location = spawn2;
whichObj = meteor2;
Debug.Log("Chose pos 2");
}
else if(randomPick == 3){
location = spawn3;
whichObj = meteor3;
Debug.Log("Chose pos 3");
}
var meteorToMake : Rigidbody = Instantiate(whichObj, location.position, location.rotation);
meteorToMake.AddForce(-Vector3(0,0,500));
yield WaitForSeconds(1);
spawning = false;
}
What I would like is to also choose the object that spawns from the spawn point randomly... Any ideas?
Answer by bompi88 · Apr 27, 2012 at 06:08 PM
Try this:
var timer : float = 0.0;
var spawning : boolean = false;
var meteors : Rigidbody[];
var spawnPoints : Transform[];
function Update () {
if(!spawning){
timer += Time.deltaTime;
}
if(timer >= 1.5){
Spawn();
}
}
function Spawn(){
spawning = true;
timer = 0;
var randomSpawnPick : int = Mathf.Abs(Random.Range(0,spawnPoints.length-1));
var randomRigidPick : int = Mathf.Abs(Random.Range(0,meteors.length-1));
var location : Transform;
var whichObj : Rigidbody;
location = spawnPoints[randomSpawnPick];
whichObj = meteors[randomRigidPick];
var meteorToMake : Rigidbody = Instantiate(whichObj, location.position, location.rotation);
meteorToMake.AddForce(-Vector3(0,0,500));
yield WaitForSeconds(1);
spawning = false;
}
what's all this about 'var thisG : GameObject; var enemies : GameObject[]; var closestEnemy : GameObject;'
Sorry, you can delete those.. I pasted it in an old file, for editing. Some of the old stuff came along.. Are you sure you don´t want any enemies in your game :-P hehe..
Haha, i have plenty of enemies but no random spawning required. Was just wondering if i was missing something.
Your answer
![](https://koobas.hobune.stream/wayback/20220613070833im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I make a game object spawn several times in semi-random locations? 1 Answer
Enemies spawn on top of each other(C#)(Unity) 1 Answer
AI spawning areas. What are the ways to make them? 1 Answer
How to spawn random buildings 5 Answers
Creating a random number of spawning items on collision 2 Answers