Finding the nearest target in unity

Can anyone help me? I don't know what's wrong but my script isn't working when I have more than 2 targets.

GameObject[] cores;
GameObject closest_core = null;
cores = GameObject.FindGameObjectsWithTag ("bldg_core");

if (cores.Length != 1)
    for (int x = 0; x < cores.Length - 1; x++) 
    {
        if (distanceToPlayer (cores[x + 1]) < distanceToPlayer (cores[x]))
            closest_core = cores [x + 1];
    }

Upvotes: 0

Views: 1822

Answers (2)

Daniel
Daniel

Reputation: 7724

You are not comparing the current GameObject of the loop with the closest.

You should do something like:

GameObject[] cores;
GameObject closest_core = null;
float dist, minDist = 999999f;
cores = GameObject.FindGameObjectsWithTag ("bldg_core");
for (int x = 0; x < cores.Length; x++) {
    dist = distanceToPlayer (cores [x]);
    if(dist < minDist){
        minDist = dist;
        closest_core = cores[x];
    }
}

Upvotes: 1

ryeMoss
ryeMoss

Reputation: 4343

You will need to store the closest core as you loop through. At the moment you are only comparing the current object distance in the array to the next object distance.

    GameObject[] cores
    GameObject closest_core = null;

    cores = GameObject.FindGameObjectsWithTag ("bldg_core");
    if (cores.Length != 1)
        for (int x = 0; x < cores.Length - 1; x++) {
            if (distanceToPlayer (cores [x + 1]) < distanceToPlayer(closest_core))
                closest_core = cores [x+1];
        }

Upvotes: 1

Related Questions