Finding next nearest enemy, in line of sight
Hello all
Im trying to figure out how to make my Enemy AI find the next nearest target, in his line of sight. Right now - He does aqquire a target, but he doesnt switch to the next nearest targets, when the "player / ai" is behind a wall. The script look like this:
///Script
public GameObject FindClosestEnemy() {
GameObject[] Enemies;
Enemies = GameObject.FindGameObjectsWithTag("Target_Tag");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
Collider[] hitColliders = Physics.OverlapSphere(myTransform.position, Min_Distance, 1 << 20);
int i = 0;
if (i < hitColliders.Length)
{
foreach (GameObject Enemy in Enemies)
{
Vector3 ShootDirection = Enemy.transform.position - Muzzle_Point.transform.position;
RaycastHit Hit;
if (Physics.Raycast(Muzzle_Point.transform.position, ShootDirection, out Hit, squareRange, 1 << 20))
{
Vector3 diff = Enemy.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = Enemy;
distance = curDistance;
}
}
else
{
closest = null;
return null;
}
}
}
return closest;
}
The problem as i see it, is the "Else" part. I think i need to add the Targets to a list, that you can switch from, but i dont know how to implement it. So far ive tried around 8 hours to get over this problem. Any help in form of code would be appriciated!
Best regards!
Your answer

Follow this Question
Related Questions
How to perform this Word Game 0 Answers
Gameobject list does not retrieve the first index in for loop 0 Answers
Instantiating GameObject and Adding to list 3 Answers
Stucked in a infinite loop and don't know why 2 Answers
replace GameObjects in game with other GameObjects using raycast detection. 0 Answers