- Home /
Instantiate a Prefab along the surface of another GameObject (Sphere)
I'm trying to instantiate a prefab randomly along the surface of another object, in my case its a sphere, I have no idea how to go about such a thing.
var grass : GameObject;
function Start() {
var grassNum = Random.Range(300, 400);
for (var i = 0; i < grassNum; i++){
var position = Vector3(Random.Range(-5.0, 5.0), 0.5, Random.Range(-5.0, 5.0));
var grassScale : float = Random.Range(0.1,0.3);
var tempObj = Instantiate(grass, position, Quaternion.identity);
tempObj.transform.eulerAngles.y = Random.Range(0, 360);
}
}
Cheers - C
Answer by Jesse Anders · Feb 21, 2011 at 11:38 AM
You can use Random.onUnitSphere to generate random positions for the objects.
Generating the orientation is a little trickier. The easiest solution would probably be to use Quaternion.FromToRotation() to generate a rotation that rotates the 'up' vector for each object into alignment with the surface normal. (The surface normal will simply be the return value of Random.onUnitSphere prior to any scaling that you apply.)
I was thinking about using a modified LookAt.js to face my refab towards an empty GameObject at the center of the sphere. Thats should be a quick fix. Thanks a lot.
Your answer
Follow this Question
Related Questions
Randomly Instantiating an object inside a shrinking sphere? 1 Answer
Instantiating a random prefab. 2 Answers
gameobject spawn in randomrange coordinates 1 Answer
instantiate random prefabs based on player camera distance 1 Answer
Random Spawn 2 Answers