Random instantiate with while loop

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?

i “think” i know what your trying to do, but I’m not sure so forgive me if its not lol also this code isn’t tested, so just use the idea of it and try to put it in your code,

you want each instance you make to then cast a ray down to the ground right? if so you can store each instance as a variable like this

    var thisPrefab = Instantiate(prefab, transform.position, transform.rotation)

    if (Physics.Raycast (thisPrefab.transform.position, -Vector3.up, hit))
   {
    distanceToGround = hit.transform.position;
   }

It looks really promising, thanks, i will try this.

It works well!

what i did now, thanks to some tests and researchs is:

if (Physics.Raycast (thisPrefab.transform.position, -Vector3.up, hit)) {
			
			distanceToGround = hit.transform.position;
			thisPrefab.transform.position = hit.point;
			
			
			}

which gives me a precise distance from the closest floor and stick each instance on it! this is absolutely perfect. I now have to take care of the rotation of each instance, THanks for your Help, sir!