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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Closest game object script not working C#.

Discussion in 'Scripting' started by Epic-Username, Jul 24, 2015.

  1. Epic-Username

    Epic-Username

    Joined:
    May 24, 2015
    Posts:
    339
    This is so annoying, i have no idea why its not finding closest object and setting it as "closest". Can someone please tell me whats wrong with this.

    Code (CSharp):
    1. for(int i = 0; i < weaponsOnGround.Count;i++){
    2.                 distance = Mathf.Abs(transform.position.x + transform.position.z) - Mathf.Abs(weaponsOnGround[i].transform.position.x - weaponsOnGround[i].transform.position.z);
    3.                 Checking = weaponsOnGround[i];
    4.                 if(closest == null)closest = Checking;
    5.                 if (distance < Mathf.Abs(closest.transform.position.x + closest.transform.position.z)) closest = Checking;
    6.             }
     
  2. kemar

    kemar

    Joined:
    Nov 4, 2014
    Posts:
    15
    Hi,
    Calcul distance with the function Vector.Distance(). This should be work
    Code (CSharp):
    1. Vector2.Distance(vec1, vec2)
     
  3. Epic-Username

    Epic-Username

    Joined:
    May 24, 2015
    Posts:
    339
    I'm using vector3's and i cant compare vectors with < or >.
     
  4. Velcrohead

    Velcrohead

    Joined:
    Apr 26, 2014
    Posts:
    78
    I'm not certain but I think you can use the following to get the distance.

    Code (CSharp):
    1. float distance = (Vector1 - Vector2).magnitude;
     
  5. A.Killingbeck

    A.Killingbeck

    Joined:
    Feb 21, 2014
    Posts:
    483
    Vector2.Distance returns a float
     
  6. tedthebug

    tedthebug

    Joined:
    May 6, 2015
    Posts:
    2,570