Instantiating Object On Map

Before I start with the question, I already searched the forum for a solution, but was unable to get any to work for me.

Basically, I have an overhead camera looking down at my map from an angle. What I want, is to Instantiate the object on the map wherever I click.

Right now my script is this

#pragma strict

var object : GameObject;
var distanceAway : float;   
var rayHit : RaycastHit;    
var a : Vector3;   

function Start () {  

function Update () {  
    if(Input.GetMouseButtonDown(0)) { 
        if(Physics.Raycast(transform.position, Vector3.down, rayHit)) {
            distanceAway = rayHit.distance;

        a = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y,distanceAway));

        Instantiate(object, a, Quaternion.identity);

The code does instantiate an object somewhat where I want it to, but it is at the wrong height. It’s because the ray distance is from my camera to the ground, and not from my mouse cursor to the ground, if that makes any sense. I can’t seem to find a solution to get the object to instantiate at the same height as the ground. Any help would be greatly appreciated!

Update: I’ve been experimenting further and find, as long as my camera is facing directly at the ground (a 90 angle directly at the ground) and the terrain below me is flat, then the objects instantiate on the terrain right. The problem is I need to have my camera at an angle, and somehow compensate for that when I instantiate.

Update: Wow… I have spent literally 20+ hours researching this subject, experimenting, trying code, etc… Then while looking into casting rays according to local rotation I just happen to stumble across the answer… haha weird how things work out.

Not sure about this, as I haven’t tried this out in Unity yet, but perhaps you could simply use “rayHit.point” for the coordinates to instantiate your object…?

I’ll check if this works and edit my comment…