Generate an object in random positions ?


I tried to generate an object in random positions but it didn’t work good,
it was generating very fast, i didn’t know why? also the rotation is generating
in weird way, I wanted all the rotation as the original object, I used this code:

#pragma strict

var theObject:Transform;
var theNewPos:Vector3;
var maxPos:int=2000;
var minPos:int=9;
var max=1;
var i = 0;

function Start(){


function Update(){




function spawn() {

theNewPos= new Vector3 (Random.Range(minPos,maxPos),0,Random.Range(minPos,maxPos));



Here is a rewrite of your code. I made a lot of changes which I usually don’t like to do.

var theObject:GameObject;
var maxPos:float = 2000.0;
var minPos:float = 9.0;
var max = 22;

function Start(){

    function spawn() : IEnumerator {
    	for (var i = 0; i < max; i++) {
    		yield WaitForSeconds(2.0);
    		var theNewPos= new Vector3 (Random.Range(minPos,maxPos),0,Random.Range(minPos,maxPos));
    		var go : GameObject = Instantiate(theObject);
    		go.transform.position = theNewPos;

A few comments:

  • Positions and positions in Unity are float values. While int variables can be converted, there are some bugs that pop out when using ints instead of floats.
  • If you call Instantiate() without parameters, it uses the position and rotation of the original object. Then on the next line I set the position, but left the rotation alone.
  • Your method of trying to spawn one every 2 seconds would not work. You could have done a timer implemented in Update() rather than the solution I have here.