- Home /
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
Answer by johan-skold · Feb 20, 2011 at 07:29 PM
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); } }
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!
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)