RTS Mouse Click Movement

Hello,

Currently I have the ability to select a unit on the map. I’m very new to unity scripting, so before I implemented path finding I wanted to see if I could just automatically move the selected object to a point on the map that I click on. The code that I have come up with through some research:

		var mousePo = Camera.main.ScreenToWorldPoint (Vector3 (Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane));
		var hit: RaycastHit;
		var ray = Camera.main.ScreenPointToRay(mousePo);
	
		if(Physics.Raycast(ray.origin,ray.direction, hit))
		{
			transform.position = mousePo;
		}

The camera I am using is above the terrain with an X rotation of 40 looking down onto the terrain from an angle (as is common in most RTS from my experience.) The problem seems to be that it is spawning the object at my camera location and dropping it onto the map below the camera, which is obviously not the desired effect. Could someone please point me in the right direction on how I can accomplish this?

1: Get the position of the mouse click and make it a target start the going .

2: Check if the target is close to the object.

3: Make the object look at the target with transform.LookAt(target);

4: Get the object moving there with transform.Translate(0, 0, Time.deltaTime);

5: Distance is close enough, we close the moving

    var target:Transform;
    var going:boolean;

    function Start(){
      target.position =transform.position;
      going =false;} 

    function Update(){
      if(Input.GetMouseButtonDown(0)){       // the button is pressed
        target.position=Input.mousePosition;        
        going = true;}

     if(going){
        if((Vector3.Distance(target.position,transform.position))>0.5){       
          transform.LookAt(target);          
          transform.Translate(0, 0, Time.deltaTime);   
     }
     else 
        going =false;    
   }

EDIT: I added a Start function to resolve your problem. Also, I added an if statement that would solve some later problems (5:) Sorry I have been reediting as I found mistakes on my scripts…

For the distance I put 0.5 because if you compare with 0 it might never really reach it and your object would keep on trying moving around the target without stopping on it.