x


Randomly position Instantiated GameObject's

I've recently just enquired about randomly instantiating a gameobject, but now I've got a problem randomising there position, I've managed to get the position to randomise but this apples to all the instances. I want each instance to have its own random position.

var grass : GameObject;

function Start() {
     var grassNum = Random.Range(4, 10);
     var position = Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
     for (var i = 0; i < grassNum; i++){
        Instantiate(grass,position, Quaternion.identity);
     }
}

Thanks - C

more ▼

asked Feb 20 '11 at 07:22 PM

Caiuse gravatar image

Caiuse
787 83 104 122

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

If so you need to generate the position inside the for loop as well, to make sure it runs the same amount of times.

var grass : GameObject;

function Start() {
    var grassNum = Random.Range(4, 10);
    for (var i = 0; i < grassNum; i++){
        var position = Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
        Instantiate(grass,position, Quaternion.identity);
     }
}
more ▼

answered Feb 20 '11 at 07:29 PM

johan-skold gravatar image

johan-skold
384 2 4 15

I don't suppose you know how to change the Quaternion.identity to randomise just on the X, i tried Random.rotation but its on x,y,z? thanks for your answer!

Feb 20 '11 at 07:43 PM Caiuse

I assume you mean the X-value that shows up in the inspector? That is, you want to rotate randomly around the X-axis? If so, try; Quaternion.AngleAxis(Random.Range(-180.0f, 180.0f), transform.right)

Feb 21 '11 at 07:14 AM johan-skold
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1683
x886
x580
x575

asked: Feb 20 '11 at 07:22 PM

Seen: 2565 times

Last Updated: Feb 20 '11 at 07:22 PM