Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Issue with looping over list with foreach

Discussion in 'Scripting' started by AlexTheGreat123, Mar 18, 2022.

  1. AlexTheGreat123

    AlexTheGreat123

    Joined:
    Jun 25, 2020
    Posts:
    3
    I'm trying to create a grapple sort of system and when I'm trying to find the nearest object, it returns this error:

    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. Grappler.<Update>g__FindClosestObject|5_0 (System.Single range) (at Assets/Scripts/Grappler.cs:80)
    3. Grappler.Update () (at Assets/Scripts/Grappler.cs:27)
    4.  
    This is the code in question
    Code (CSharp):
    1.             GameObject FindClosestObject(float range)
    2.             {
    3.                 GameObject[] objects = GameObject.FindGameObjectsWithTag("Object");
    4.  
    5.                 GameObject closest = null;
    6.                
    7.  
    8.                 foreach(GameObject i in objects)
    9.                 {
    10.                     float distance = Vector3.Distance(transform.position, i.transform.position);
    11.  
    12.                     float closestDistance = Vector3.Distance(transform.position, closest.transform.position);
    13.  
    14.                     if (distance <= closestDistance)
    15.                     {
    16.                         closest = i;
    17.                     }
    18.  
    19.                 }
    20.                 return closest;
    21.             }
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,529
    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.
     
  3. LilFire

    LilFire

    Joined:
    Jul 11, 2017
    Posts:
    74
    closest is null the first iteration.
     
    AlexTheGreat123 likes this.
  4. AlexTheGreat123

    AlexTheGreat123

    Joined:
    Jun 25, 2020
    Posts:
    3
    Sorry, I thought this was a general 2D forum, my bad.
     
  5. AlexTheGreat123

    AlexTheGreat123

    Joined:
    Jun 25, 2020
    Posts:
    3
    Thanks, fixed it