Raycast + Instantiate

Hello there,

This script is called "Raymouse" and it's inside the main camera:

public var turretModel: GameObject;

function Update () {

    var ray: Ray = camera.ScreenPointToRay (Input.mousePosition);
    //Debug.DrawRay (ray.origin, ray.direction * 10, Color.yellow);
    var raycastHit: RaycastHit;

    if(Physics.Raycast(transform.position, ray.direction, raycastHit)){
    //print("RaycastHit " + raycastHit.collider.gameObject.name);   

    if(raycastHit.collider.gameObject.name=="base"){
        if(Input.GetKeyDown("mouse 0")){
            var newTurret: GameObject;

            newTurret = Instantiate(turretModel, raycastHit.collider.gameObject.transform.position, raycastHit.collider.gameObject.transform.rotation);

            Destroy(raycastHit.collider.gameObject);

            }
    }

    }
}

It instantiates an object when the user clicks a certain game object. But, depending on the order in which the objects are instantiated, it blocks when you try to instantiate something behind. I have attached a picture which shows what I just meant:

alt text

For it to work, I have to instantiate the ones in the back first. But it would be good if it worked in any order.

You should give jester the up vote as he pretty much answered your question. Also, if you don't need to click on the blocks again after setting them you can change them to the ignore rays layer

Another solution might be using capsule colliders instead of sphere colliders, if you are using cylinders