I created an array with a list of targets.
GameObject[] target = GameObject.FindGameObjectsWithTag(enemyTag);
foreach (GameObject go in target)
{
path.Add(go.transform);
}
During the game, the player looks for the closest one.
int findClosestTarget()
{
if (path.Count == 0) return -1;
int closest = 0;
float lastDist = Vector3.Distance(this.transform.position, path[0].position);
for(int i = 1; i < path.Count; i++)
{
float thisDist = Vector3.Distance(this.transform.position, path*.position);*
if(lastDist > thisDist && i != currentTarget)
{
closest = i;
lastDist = thisDist;
}
}
return closest;
}
But sometimes, one of those targets gets destroyed and I get an error message (NullReferenceException: Object reference no set to an instance…). I assume I have to remove it from the array so I tried the following both in Update and in the findClosestTarget function
if (path[currentTarget] = null)* *path.Remove(path[currentTarget]);
but that did not work and I keep getting the error message. What is the correct way of removing the destroyed target from the array?