James
James

Reputation: 21

why finding the second closest object sometime return null?

I try to find the closest and second closest object by using the code below. However there is a little bug while I was using it. When the player move away from the second closest object sometime the result return null. Anyone know what causing this? I have included the debug.drawline picture as well which shows the problem.

enter image description here

enter image description here

    public GameObject[] FindClosestEnemy()
    {
        GameObject[] gos;
        gos = GameObject.FindGameObjectsWithTag("Agents");
        GameObject closest = null;
        GameObject secondClosest = null;
        float distance = Mathf.Infinity;
        Vector2 position = transform.position;
        foreach (GameObject go in gos)
        {
            Vector2 diff = (Vector2)go.transform.position - position;

            float curDistance = diff.sqrMagnitude;
            if (curDistance < distance)
            {
                secondClosest = closest;
                closest = go;
                distance = curDistance;
            }
        }

        Debug.DrawLine(position, closest.transform.position);
        Debug.DrawLine(position, secondClosest.transform.position);

        Debug.Log("1" + "and" + closest);
        Debug.Log("2" + "two" + secondClosest);
        //Debug.Log(gos[1]);

        return new GameObject[] { closest, secondClosest };
    }

Upvotes: 1

Views: 73

Answers (2)

8protons
8protons

Reputation: 3959

You initialize secondClosest to be null here

GameObject secondClosest = null;

and later have logic that conditionally assigns secondClosest

if (curDistance < distance)
{
   secondClosest = closest;
   closest = go;
   distance = curDistance;
}

So if your condition does not hold, then secondClosest remains null as you initialized.

If the condition does hold, you assigned secondClosest to point to whatever closest is pointing to, which is currently null. You later try to assign closest = go, but that changes where closest points to, not secondClosest, which still points to a null reference. Here's an example with arrays:

https://dotnetfiddle.net/BafOSW

Upvotes: 1

joll05
joll05

Reputation: 452

In your code, if an enemy is further away than the current closest enemy it will be ignored completely. Therefore, if the closest enemy comes before the second closest in the array you get from GameObject.FindGameObjectsWithTag("Agents") then the second closest enemy won't be correct.

Upvotes: 1

Related Questions