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

Help with checking distance for each element in the list?

Discussion in 'Scripting' started by pretender, Mar 4, 2015.

  1. pretender

    pretender

    Joined:
    Mar 6, 2010
    Posts:
    862
    Hi,
    I have the list of Vector3's. I want to compare each Vector3 with each element in the list and perform action if distance is greater than 10 for example...

    I have this code that hangs unity, and I don't know why, it should work?

    Code (CSharp):
    1. for (int i = 0; i < controller.Model.Positions.Length; i++)
    2.         {
    3.             var x = controller.Model.Positions[i];
    4.  
    5.             for (int j = 0; j < controller.Model.Positions.Length; j++)
    6.             {
    7.                 if (i == j) continue;
    8.  
    9.                 var y = controller.Model.Positions[j];
    10.              
    11.                 if(Vector3.Distance(x,y) > 10.0f) Debug.Log("distance greater than 10 for: " + i + " " + j);
    12.             }
    13.         }
    14.  
     
  2. Strategos

    Strategos

    Joined:
    Aug 24, 2012
    Posts:
    255
    Is there an error ?

    How many positions do you have ?

    If there are tonnes of debug messages it can freeze things up for quite a while ?
     
  3. pretender

    pretender

    Joined:
    Mar 6, 2010
    Posts:
    862
    I put it in coroutine and it works fine, it was freezing on debug messages, many of them print!
    is there any other more efficient way of this kind of loop?

    thanks for looking into this!
     
  4. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    If you set j to i+1 instead of 0 then you'll avoid repeating evaluations for items at the beginning of the list.