Tower, get target within range by mouseclick

Hello!
I am working on a tower shooter script where I have made the tower shoot at random targets within a certain range. I am now trying to make it so that when I ctrl-click an enemy I wan’t the tower within range to start firing at this target. It does already shoot at my target but they can shoot across the whole map. I need help on limiting the range of the target-shooting. Here is what I’ve got so far:

private var target;
private var posTarget : Vector3;
public var projectile : Rigidbody;
private var cloneProjectile;
public var projectileSpeed : float = 900;
public var skottEld : GameObject;
private var cloneSkottEld;
private var center : Vector3;




//private var getParent : GameObject;

private var nextShot = 0.0;
var reloadTime = 0.5;




function Update () { 
	
//Controll attacks
if(Input.GetKey(KeyCode.LeftControl)){
	if(Input.GetKeyDown(KeyCode.Mouse0)){
		var hitTower : RaycastHit;
			
			if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hitTower)){
			
			
			
			if(hitTower.collider.tag == "Enemy"){
				target = hitTower.collider.gameObject;
				}
				
				
			}
			
	}
}

gameOver = HPTower.gameOver;
if(gameOver == true){
	Destroy(this.transform.root.gameObject);
}


if(target == null){
	target = transform.root.GetComponent(Detector).target;
}

//target = Detector.target();
	//target = GameObject.FindGameObjectWithTag("GUISHOP").GetComponent(Buy).DMGUpgrade;
	if(target != null){
	
		posTarget = Vector3(target.transform.position.x,target.transform.position.y,target.transform.position.z);
		this.transform.LookAt(posTarget);
	if(Time.time > nextShot){
		nextShot = Time.time + reloadTime;
	
		
		
		
		
		
		
		
		cloneProjectile = Instantiate(projectile, transform.position, transform.rotation);
		
		
		cloneProjectile.SendMessage("getTarget", target);
		//cloneProjectile.rigidbody.AddForce(cloneProjectile.transform.forward * projectileSpeed); 
		Destroy(cloneProjectile.gameObject, 6);
		
		//cloneSkottEld = Instantiate(skottEld, transform.position, transform.rotation);
		//Destroy(cloneSkottEld, 3);
		
		
	}
	}
	
	

		
}

This is the script that get the target position and then starts firing at it.
And this script detects enemies in the range and then sends a target to the firing script:

public var target : GameObject;


function OnTriggerStay(hitTarget : Collider){

	if(hitTarget.gameObject.tag == "Enemy" && target == null){
		target = hitTarget.gameObject;
		

	}
	
}

Thanks in advance! //Simon

I’m having some difficulty deciphering your logic in the script, but something like this should do the trick. Make a float variable called range, specifying the range you want the tower to have. After you cast the ray to see if a target was clicked:

float distance = Vector3.Distance(myTowerPosition, myIntendedTargetPosition);
if (distance <= range) {
	//set the target, fire projectile, etc
}