Issue with looping over list with foreach

I’m trying to create a grapple sort of system and when I’m trying to find the nearest object, it returns this error:

NullReferenceException: Object reference not set to an instance of an object
Grappler.<Update>g__FindClosestObject|5_0 (System.Single range) (at Assets/Scripts/Grappler.cs:80)
Grappler.Update () (at Assets/Scripts/Grappler.cs:27)

This is the code in question

            GameObject FindClosestObject(float range)
            {
                GameObject[] objects = GameObject.FindGameObjectsWithTag("Object");

                GameObject closest = null;
               

                foreach(GameObject i in objects)
                {
                    float distance = Vector3.Distance(transform.position, i.transform.position);

                    float closestDistance = Vector3.Distance(transform.position, closest.transform.position);

                    if (distance <= closestDistance)
                    {
                        closest = i;
                    }

                }
                return closest;
            }

This is the 2D forum. May I ask what your post has to do with 2D specifically? I’m not seeing it.

We have a dedicated scripting forum for generic scripting questions. I’ll move your post.

closest is null the first iteration.

1 Like

Sorry, I thought this was a general 2D forum, my bad.

Thanks, fixed it