Hello , i’m using a script to instantiate some objects over random positions:
// Instantiates prefab somewhere between -10.0 and 10.0 on the x-z plane
var prefab : GameObject;
var x : int;
var i = 0;
function Start () {
var position: Vector3 = Vector3(Random.Range(-10.0, 10.0), 0, Random.Range(-10.0, 10.0));
if(x > 0) // condition de base: que le nombre ne soit pas encore épuisé
while ( i < x ) //tant que x est toujours + grand que zero
{
Instantiate(prefab, Vector3(Random.Range(-10.0, 10.0), 0, Random.Range(-10.0, 10.0)), Quaternion.identity);
i ++;
}
}
it works really fine, but now i’m trying to raycast each one of them clones to stick it to the floor; i’m just learning so i found a code which works fine alone:
var hit : RaycastHit;
if (Physics.Raycast (this.transform.position, -Vector3.up, hit)) {
distanceToGround = hit.transform.position;
this.transform.position = hit.point;
}
but, i have to assign this to every clone i generate, so i tried to insert a ‘if’ in it, like following:
while ( i < x ) //tant que x est toujours + grand que zero
{
Instantiate(prefabinst, Vector3(Random.Range(-10.0, 10.0),0, Random.Range(-10.0, 10.0)), Quaternion.identity);
if (Physics.Raycast (prefabinst.transform.position, -Vector3.up, hit)) {
distanceToGround = hit.transform.position;
print("Distance: "+distanceToGround);
}
i ++;
}
but looks like it raycasts for the first of them only, whereas i’d like each clone to detect the floor, and then stick on it; apparently i can’t make this operation for each instance in the ‘while’ loop, i’m not sure if i should use ‘foreach’, …
For now i’ve put the ‘stick’ script on the base prefab, and it works, but i was thinking maybe of a better, less demanding way?