Detect gameObjects within range and assign them as movetarget


I am making a towerdefence game and atm trying to make my enemy AI script be abit smarter. I want the AI to when spawned start moving towards the “Tower” tag but when encountering “MiniTower” tag with spherecollider it should change target and move towards that target instead. They are atm just moving towards the “Tower” tag and ignoring anything on the way. Here is the scripts:

private var anyTargetLeft;
private var target : GameObject;	
public var targetPos : Vector3; //to be able to jump(why its public)
public var damage : int = 15;

private var findTarget : boolean = true;

public var moveSpeed : float = 10;
private var grounded : boolean = true;

function Start () {
this.enabled = true;

function Update () {

this.gameObject.transform.Translate(Vector3(0,0,Time.deltaTime * moveSpeed));

//Destroys this script so it wont lagg when you loose
	var anyTargetLeft = GameObject.FindGameObjectWithTag("Tower").gameObject;
if(anyTargetLeft == null){

target = this.gameObject.transform.root.gameObject.GetComponent(EnemyDetector).targetSphere;

if(target.gameObject == null){
	findTarget = true;

if(findTarget == true){

if(target == null){
	target = GameObject.FindGameObjectWithTag("Tower").gameObject;
	//findTarget = false;

//findTarget = false;
targetPos = Vector3(target.gameObject.transform.position.x,this.gameObject.transform.position.y,target.gameObject.transform.position.z);



function OnCollisionEnter(targetHit : Collision){

//main tower
	if(targetHit.gameObject.tag == "Tower"){
		var objectHit = targetHit.gameObject;
		objectHit.GetComponent(HPTower).towerApplyDMG(damage); //gånger gamelvl senare
	//small towers
	if(targetHit.gameObject.tag == "MiniTower"){
		objectHit = targetHit.gameObject;
		objectHit.GetComponent(MiniTowerHP).towerApplyDMG(damage); //gånger gamelvl senare

And this one is detecting towers if they come within the spherecollider and then telling that they are the target:

public var targetSphere : GameObject;

function OnTriggerStay(hitTarget : Collider){
	if(hitTarget.collider.gameObject.tag == "Tower" || hitTarget.collider.gameObject.tag == "MiniTower"){
		targetSphere = hitTarget.gameObject;

You could have a sphere collider set to a trigger. Its radius would be set to the distance from the tower that you want your AI to start attacking it.

You need to make sure you tag your enemies, then when something enters the trigger collider you can check if it’s an enemy, and if so change its target.

Something like this:

void OnTriggeEnter(Collider other)
	// Check if an enemy entered the trigger
	if(other.gameObject.tag == "Enemy")
		//Set the new target here = blahhhh;