Move from one target to another

Lads,

I’m trying to move from one game object to another, destroying the game objects as I go. The character moves to the first target preperly but then gets stuck and will not proceed to the next target. Here’s the code:

using UnityEngine;
using System.Collections;

public class EnemyAI_2 : MonoBehaviour {
	
		public Transform target;
		public Transform target2;
		public int moveSpeed;
		public int rotationSpeed;
		public float maxDistance = .5f;
		public GameObject otherGameObject;
		
		private Transform myTransform;
		private NavMeshAgent agent;
		private Strike_Timer strikeTimer;
		
		
		void Awake () {
			myTransform = transform;
		strikeTimer = otherGameObject.GetComponent<Strike_Timer>();
		}
		
		void Start () {
			agent = GetComponent<NavMeshAgent> ();
			
		}
		
		void Update () {
			
			GameObject go = GameObject.FindGameObjectWithTag("Tower1");
			
			target = go.transform;
			Debug.DrawLine(target.position, myTransform.position, Color.yellow);
			
			//Look at Target
			myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
			
			if (Vector3.Distance(target.position, myTransform.position) > maxDistance) {
				//move towards Target
				myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
			}
			if(strikeTimer.countdown <= 0.0f)
			{
				GameObject go2 = GameObject.FindGameObjectWithTag("baseCenter");
				target2 = go2.transform;
				Debug.DrawLine(target.position, myTransform.position, Color.yellow);
			
			//Look at Target
			myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
			
			if (Vector3.Distance(target.position, myTransform.position) > maxDistance) {
				//move towards Target
				myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;

			}
		}
		
	}
}

Any thoughts?

Stef

Assuming you’ve verified that strikeTimer.countdown goes below 0.0, then what you have is fighting conditions. That is, even after the countdown timer is below 0.0, you still try to move towards ‘Tower1’ on line 40, just as you are trying to move towards ‘baseCenter’ on line 53. Both lines are being executed and fighting with each other.

My suggestion is to restructure your code so that the target finding is done in a separate routine and only called once for each target. That code would set a class instance variable ‘target’ and the Update() code would move towards whatever is set to target. So line 30 gets moved to another function called from Start(). Lines 42 - 56 get change to something like:

if (strikeTimer.countdown <= 0.0) {
     FindNewTarget();
     strikeTimer.countdown = 20.0f;
}

FindNewTarget() would walk down a list setting ‘target’ to something new each time called.