Jip Harthoorn
Jip Harthoorn

Reputation: 302

Unity3d C# - Find second closest cube

I have this script to find the current closest cube:

GameObject FindClosestCube() {

    GameObject[] gos;
    gos = GameObject.FindGameObjectsWithTag("cube");
    GameObject closest = null;
    float distance = Mathf.Infinity;
    float position = transform.position.z;
    foreach (GameObject go in gos) {
        float diff = go.transform.position.z - position;

        float curDistance = diff;
        if (curDistance < distance) {
            closest = go;
            distance = curDistance;
        }
    }
    return closest;
}

Now I would like to get the second closest cube, so the closest cube after the closest cube (z-axis). I tried a few things, but they didn't work so could someone explain me how to achieve this? Thanks.

Upvotes: 0

Views: 691

Answers (1)

Iggy
Iggy

Reputation: 4888

Just before assigning a new closest, assign the current value of the closest to the second closest. Then return an array of game objects, the first element being the closest.

GameObject[] FindClosestCubes() {
    GameObject[] gos;
    gos = GameObject.FindGameObjectsWithTag("cube");
    GameObject closest = null;
    GameObject secondClosest = null;
    float distance = Mathf.Infinity;
    float position = transform.position.z;
    foreach (GameObject go in gos) {
        float diff = go.transform.position.z - position;

        float curDistance = diff;
        if (curDistance < distance) {
            secondClosest = closest;
            closest = go;
            distance = curDistance;
        }
    }
    return new GameObject[] { closest, secondClosest };
}

Upvotes: 2

Related Questions