Instantiate multiple objects and have them raycast

Hey everyone,

This is my first forum post. I am rather new to unity and even newer to JavaScript this is my second week with it. So basically to get to the point I've been playing around with a script that randomly adds an object within the boundaries of the playing field.

    var floorHeight = -0.8f;// y axis
    var xAxis;
    var zAxis;
    var mine : GameObject;
    var spawn = 0;

    function Update () {

    while (spawn <= 1)
        var xAxis = Random.Range(-18,18);
        var zAxis = Random.Range(-17,21);
        Instantiate(mine, Vector3(xAxis, floorHeight,zAxis), Quaternion.identity);


This script works exactly as planned, but my playing field is uneven (a sea floor). So then I did some research and found out about something called a ray cast. I found that you can get the distance with it so with some basic logic I figured that if i subtract the distance from the mines Y position it would be on top of the sea floor. Here the script.

var toGround = false;
var obj : GameObject;

function Update () {
if (toGround == true)
    var hit : RaycastHit;
    if (Physics.Raycast (obj.transform.position, -Vector3.down, hit))
    Debug.DrawRay(transform.position, Vector3.down * 10,;
    var distanceToGround = hit.distance;
    var coll : Collider = obj.GetComponent(Collider);
    var bottom = coll.bounds.max.y;
    obj.transform.position.y = obj.transform.position.y - distanceToGround + bottom;
    toGround = false;

Now the problem is they both work as there individual functions. One randomly spawns and one moves the mine. However the mines that are added through the RandomSpawn script do not get moved to the surface. I'm pretty stumped and any help would be much appreciate. Also the RandomSpawn script is attached to an empty gameobject and the raycast script is attached to the mines that are spawned in a prefab. Anything that needs clarification please reply.

Thanks in advanced, Mike G.

I figured it out!

if (Physics.Raycast (obj.transform.position, -Vector3.down, hit))

I changed the above to the below

  if (Physics.Raycast (obj.transform.position, Vector3.down, hit))

I'm not quite sure why it worked when the object was already there, but i assume that for the prefab the ray cast was going the wrong way! Hope this helps others.

  • Mike G.