- Home /
Select/attack closest target array
Hey Guys,
I have a horde of Zombies (of course) that are attacking a group of towers, each tagged "Tower". The script works okay, but I want the zombies to attack the closest building first, then the next closest, and so on. I'm sure I need an array to do this, but have little experience. Here's my code thus far:
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public float maxDistance = .5f;
private Transform myTransform;
NavMeshAgent agent;
void Awake () {
myTransform = transform;
}
void Start () {
agent = GetComponent<NavMeshAgent> ();
}
void Update () {
GameObject go = GameObject.FindGameObjectWithTag("Tower");
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;
}
}
}
What would be the best way to add the array and make this work?
Thanks,
Stef
Answer by Alessio89 · Aug 07, 2014 at 08:30 PM
The simplest way is to iterate through an array and keep track of the closest one until you checked them all. Or you can use Linq (since you're using C#) and do something like this:
GameObject closestTower = (from tower in GameObject.FindGameObjectsWithTag("Tower") orderby Vector3.Distance(transform.position, tower.transform.position) select tower).FirstOrDefault();
This will return the closest object tagged as tower. However, you should note that: To use Linq you must include System.Linq in your usings, also you don't get much in terms of performance compared to iterating through an array or list, but it's cleaner if you ask me.
Your answer
![](https://koobas.hobune.stream/wayback/20220613160101im_/https://answers.unity.com/themes/thub/images/avi.jpg)