- Home /
Question by
FH_88 · Jan 12, 2015 at 08:29 AM ·
javascriptgameobjectrandomspawnamount
Spawn random amount apart of each other
I have a script, which spawns a random amount of gameobjects, on a random place on the screen. Now my problem is that, the amount of gameobjects are spawned in the same place so lets say It spawns an amount of five, then all five gameobjects, spawn on top of each other, where they are supposed to spread instead. How can I fix this?
This is my script so far.
var Mines : Transform;
private var Timer : float;
function Awake () {
Timer = Time.time + 4;
}
function Update () {
var randNum = Random.Range(0, 5); // this will return a number between 0 and 9
var screenPosition : Vector3 = Camera.main.ScreenToWorldPoint(new Vector3(Random.Range(0,Screen.width), Random.Range(0,Screen.height), Camera.main.farClipPlane/2));
if (Timer < Time.time) {
for (var i = 0; i < randNum; i++){
Instantiate(Mines, screenPosition, Quaternion.identity);
//Instantiate(Mines, transform.position, transform.rotation);
Timer = Time.time + 4;
Debug.Log("Spawned Mines");
}
}
}
Comment
Best Answer
Answer by HarshadK · Jan 12, 2015 at 08:34 AM
Your statement to generate random screen position should be inside your for loop, something like:
function Update () {
var randNum = Random.Range(0, 5); // this will return a number between 0 and 9
if (Timer < Time.time) {
for (var i = 0; i < randNum; i++){
var screenPosition : Vector3 = Camera.main.ScreenToWorldPoint(new Vector3(Random.Range(0,Screen.width), Random.Range(0,Screen.height), Camera.main.farClipPlane/2));
Instantiate(Mines, screenPosition, Quaternion.identity);
//Instantiate(Mines, transform.position, transform.rotation);
Timer = Time.time + 4;
Debug.Log("Spawned Mines");
}
}
Your answer
Follow this Question
Related Questions
Spawn random amount of gameobjects 2 Answers
Generate random number and set a GameObject active. 1 Answer
Spawn game object in random position on screen 1 Answer
Calling random functions 4 Answers
Random Spawner using radius and numbers 3 Answers