I have been attempting to create a system that detects all enemies inside a sphere collider and calculates their distance. So far, I have this which grabs all the objects and puts them in to a list, this works good.
private void OnTriggerEnter(Collider other)
{
if (HitBoxAI.isENEMY) {
if (other.tag == "Friendly")
{
if (!targets.Contains(other.gameObject))
{
targets.Add(other.gameObject);
}
}
if (other.tag == "Player")
{
if (!targets.Contains(other.gameObject))
{
targets.Add(other.gameObject);
}
}
}
if (HitBoxAI.isALLY)
{
if (other.tag == "Enemy")
{
if (!targets.Contains(other.gameObject))
{
targets.Add(other.gameObject);
}
}
}
Now, that all works and successfully adds the gameobjects into the list.
**What do I want?**
I want to make it so that I can run a function that will look through the list and determine the closest game object in the list to the current transform.gameObject and then to assign the AI's target to that.
So, as for pseudocode, I am trying to achieve something like;
ai.target = targets.closestInList
I can imagine another way would be using the **List.Sort** method and then just making the target the first in the index such as [0]. My experience with lists unfortunatetly is not very good, I hope someone can give a helping hand.
Many thanks.
↧