Modification of AIFollow path finding

I modified the code AIFollow.cs and i add the functions code. And this functions are GetEnemies() and FindClosest() .
I want to try Real Time Strategy game and i also use it for A* pathfinding.
There are not working. GetEnemies() create an array which includes “Target” tag of GameObjects. But it is not working. :frowning:

Any help i will appriciate.

Here is the Code:

using UnityEngine;
using System.Collections;


public class AIFollow : MonoBehaviour {
	//[RequireComponent (typeof(CharacterController))]
	public float speed = 3.0F;
	public float rotationSpeed = 5.0F;
	public float pickNextWaypointDistance = 3.0F;
	public float SearchWaypointFrequency = 0.2F;
	public float maxStop = 3;
	
	public bool continousTargetSearch = false;
	public float targetSearchFrequency = 1.0F;
	private bool canSearchAgain = true;
	public Command command = Command.Stay;
	
	public Transform target;
	private CharacterController controller;
	private AIAnimation animator;
	private Seeker seeker;
	
	public Vector3 myPosition;
	public Transform[] enemies;
	public float distance;
					
	
	// Make sure there is always a character controller
	
	public enum Command {
		Stay,
		Walk
	}
	
	
	
	public IEnumerator Start () { //public IEnumerator Start ()
		
		waypointPosition = transform.position;
		command = Command.Stay;
		controller = GetComponent (typeof(CharacterController)) as CharacterController;
		Object anim = GetComponent (typeof(AIAnimation));
		animator = anim != null ? anim as AIAnimation : null;
		seeker = GetComponent (typeof(Seeker)) as Seeker;
		
		StartCoroutine (Patrol());
		yield return new WaitForSeconds (Random.value*0.5F);
		
		if (continousTargetSearch) {
			StartCoroutine (SearchPlayer());
		}
		
		[COLOR="red"]//here is the start array operations[/COLOR]
		GetEnemies();    
		myPosition = transform.position;    
		target = FindClosest(enemies);
		distance=Vector3.Distance(target.position,transform.position);
		
		while (true) {
			FindPoint (curpoint);
			yield return new WaitForSeconds (SearchWaypointFrequency);
		}
	}
	
	private Vector3 waypointPosition;
	//private bool continuous = false;
	private Vector3[] points;
	private int curpoint = 0;
	
	public void Update () {
		//Debug.color = Color.blue;
		Debug.DrawLine (transform.position, waypointPosition, Color.blue); 
		
		//Stop();
		Start();
		/*GetEnemies();    
		myPosition = transform.position;    
		target = FindClosest(enemies);
		distance=Vector3.Distance(target.position,transform.position);*/
	}
	
	public IEnumerator SearchPlayer () {
		yield return 0;
		while (true) {
			yield return 0;
			while (!canSearchAgain) {
				yield return 0;
			}
			if (continousTargetSearch) {
				canSearchAgain = false;
				seeker.StartPath (transform.position,target.position);
			}
			yield return new WaitForSeconds (targetSearchFrequency);
		}
		
	}
	
	public void PathComplete (Vector3[] newPoints) {
		canSearchAgain = true;
		points = newPoints;
		FindPoint (0);
		command = Command.Walk;
	}
	
	public void PathError () {
		canSearchAgain = true;
	}
	
	public bool HasReachedTarget () {
		return curpoint >= points.Length;
	}
	
	public void FindPoint (int cpoint) {
		curpoint = cpoint;
		if (points == null || points.Length == 0 || curpoint >= points.Length) {	
			waypointPosition = transform.position;
			Stop ();
			return;
		}
		
		if (points.Length == 1) {
			waypointPosition = points[0];
			command = Command.Walk;
			return;
		}
		
		command = Command.Walk;
		
		waypointPosition = points[curpoint];
		Vector3 p = waypointPosition;
		p.y = transform.position.y;
		
		if (curpoint < points.Length - 1) {
			if ((transform.position-p).sqrMagnitude < pickNextWaypointDistance*pickNextWaypointDistance) {
				curpoint++;
				FindPoint (curpoint);
			}
			
		} else {
			if ((transform.position-p).sqrMagnitude < maxStop*maxStop) {
				curpoint++;
				FindPoint (curpoint);
			}
		}
	}
	
	public IEnumerator Patrol () {
		while (true) {
			if (command == Command.Walk) {
				MoveTowards(waypointPosition);
			}
			
			yield return 0;
		}
	}
	
	public void Stop () {
		command = Command.Stay;
		if (animator != null) {
			animator.SetSpeed (0.0F);
		}
	}
	
	public void RotateTowards (Vector3 position) {
		if (animator != null) {
			animator.SetSpeed (0.0F);
		}
		
		Vector3 direction = position - transform.position;
		direction.y = 0;
		
		if (curpoint == points.Length - 1  direction.sqrMagnitude < maxStop*maxStop) {
			FindPoint (curpoint);
			return;
		}
		
		if (direction.sqrMagnitude < 0.1F*0.1F) {
			return;
		}
		
		// Rotate towards the target
		transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
		transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
	}
	
	public void MoveTowards (Vector3 position) {
		Vector3 direction = position - transform.position;
		direction.y = 0;
		
		if (direction.sqrMagnitude < 0.2F*0.2F) {
			Stop ();
			return;
		}
		
		// Rotate towards the target
		transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
		transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
	
		// Modify speed so we slow down when we are not facing the target
		Vector3 forward = transform.TransformDirection(Vector3.forward);
		float speedModifier = Vector3.Dot(forward, direction.normalized);
		speedModifier = Mathf.Clamp01(speedModifier);
		
		// Move the character
		if (controller) {
			direction = forward * speed * speedModifier*speedModifier;
			controller.SimpleMove(direction);
		} else {
			direction = forward * speed * speedModifier*speedModifier;
			transform.Translate (direction*Time.deltaTime,Space.World);
		}
		
		if (animator != null) {
			animator.SetSpeed (speed * speedModifier);
		}
	}
	
	public void GetEnemies(){ [COLOR="red"]// Get enemies from the Scene [/COLOR]
		
		GameObject[] enemyObjects = GameObject.FindGameObjectsWithTag("Target");
		
		Transform[]  enemies = new Transform[enemyObjects.Length];   
		
		for (int i = 0; i < enemyObjects.Length; i++) 
		{        	
				enemies[i] = enemyObjects[i].transform;
			Debug.Log("GetEnemies() : count = " + i );
		}
		
		Debug.Log("GetEnemies() : enemy count = " + enemies.Length);
		
	}	
	
	public Transform FindClosest(Transform[] targets)[COLOR="red"] // Find Closest enemy[/COLOR] 
		{
			Debug.Log("FindClosest() : ---------------> " +targets.Length);
			
			GameObject[] enemyObjects = GameObject.FindGameObjectsWithTag("Target");
		
			float closestDistance = (enemies[0].position-myPosition).sqrMagnitude;  
			
			int targetNumber=0;
			
			for(int i=1; i<targets.Length ;i++)
			{
				
				float thisDisatance = (enemies[i].position-myPosition).sqrMagnitude;
				
					if(thisDisatance<closestDistance)
					{
						
						closestDistance=thisDisatance;
						targetNumber=i;
						
					}	
			}		
					
			return enemies[targetNumber];
			
		}		
	
	}

enemy must detect the target from an array and goes through it. Then Fire() and Destroy “target”. After getting another target from an array and goes to the next target.

I’m using the same system in a rts like game. I recommend you keep all your game logic in seperate scripts and try not to modify his scripts. It makes it much easier and less likely to break his stuff.
I can post an example later if you need it.

i try to make Tower Defence enemy AI . Enemy behave like RTS games. It decide how target closest me and change the target. Also it is my graduation project from university. if you send me an example i will appriciate you.

I have a separate script that has a reference to the ‘Seeker’ and ‘AIFollow’ scripts on the same GameObject:

public Seeker seeker;
public AIFollow aifollow;
public virtual void Start () {
   seeker = gameObject.GetComponent<Seeker> ();
   aifollow = gameObject.GetComponent<AIFollow> ();
...
public void MyLogicMethod {
  //here I change the destination of the AStar seeker
   seeker.StartPath (transform.position, currentOrder.position);
  ...

//you can also set the speed of the moving thing this way
//similarly you can set other useful attributes, such as Command
public float speed {
	get { return aifollow.speed; }
	set { aifollow.speed = value; }
}

Thank you very much.i handled it. Here is my Javascript code.

//wayFinder.js

var target : Transform;
var myPosition : Vector3;
var enemies : Transform[];
var counter : int;

var yuru:boolean=true;

var mesafe:float;

function Start () 
{    
	//counter=0;
	GetEnemies();    
	//myPosition = transform.position;    
	target = FindClosest(enemies);
	mesafe=Vector3.Distance(target.position,transform.position);
}

function Update(){

	GetEnemies(); //Called The function
	//myPosition=transform.position;
	target=FindClosest(enemies); //Called The function
	
	this.GetComponent("Seeker").StartPath(this.transform.position,target.position); //Starting aPathTo Closest //Enemy
	


}

function GetEnemies () // All the enemies must be saved in an Transform array.
{    
		var enemyObjects = GameObject.FindGameObjectsWithTag("Target");    
		enemies = new Transform[enemyObjects.Length];    

		for (i = 0; i < enemyObjects.Length; i++) 
		{        	
				enemies[i] = enemyObjects[i].transform;    
		}
}

function FindClosest (targets : Transform[]) : Transform  // Find The closest enemy inside The GatEnemies() function //or an array
{    

		var closestDistance = (enemies[0].position - myPosition).sqrMagnitude;    
		var targetNumber = 0;    
		
		for (i = 1; i < targets.Length; i++) 
		{        
				var thisDistance = (enemies[i].position - myPosition).sqrMagnitude;        
				if (thisDistance < closestDistance) 
				{            
								closestDistance = thisDistance;            
								targetNumber = i;        
				}    
		}    
	return enemies[targetNumber];
}

Also there are three major ideas that I mention :

1- You must move Seeker.cs and AIFollow.cs and wayFinder.js inside your moving GameObjects.

2- You must read the API and component of Seeker.cs , AIFollow.cs

3- Final You must RandomPathExecuter.cs must be move to the camera. Target component shuold be any emty GameObject at the center of Terrain or sth.

Thank you very much :smile: