Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by SPIGS · May 25, 2014 at 10:18 PM · c#objectforeachdistance check

Find greatest distance between a List of objects?

I have a list of randomly instantiated objects. Using a foreach loop, I'm comparing which one has the greatest distance between them and a main object. When the comparison is made I want to know which one has the greatest distance. Problem is I don't know to go about doing this:

 GameObject mainObject;
 
 foreach (GameObject object in objects){
      if (Vector3.Distance(mainObject, object){
           //What should i do?
      }
      //Other part I don't know
 }

I'm really lost with this one. I have no idea what to do. Any help would be appreciated!

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by T27M · May 25, 2014 at 10:33 PM

You can calculate and store each distance in a list and using the list's Sort() method, you can sort them from lowest to highest.

         public List<GameObject> objects = new List<GameObject> ();
         List<float> distances = new List<float> ();
     
         // Use this for initialization
         void Start ()
         {
                 foreach (GameObject obj in objects) {
                         float dist = Vector3.Distance (gameObject.transform.position, obj.transform.position);
                         distances.Add (dist);
                 }
                 
                 distances.Sort ();
                 
                 foreach (float f in distances) {
                         Debug.Log (f);
                 }
                 Debug.Log ("Greatest Distance: " + distances [objects.Count - 1]);
         }

Update

This does the same as above, but stores the object and it's distance from the main object in a dictionary. It then converts the Keys(distances) to a list and sorts them. Once the largest distance is determined we then simply look it up in the dictionary to find the gameobject it refers to.

 using System.Collections.Generic;
 using System.Linq;

 ...

         GameObject[] _objects;
         Dictionary<float, GameObject> distDic = new Dictionary<float, GameObject> ();
 
         // Use this for initialization
         void Start ()
         {
                 // Populate array for testing purpose - use your array of objects
                 _objects = GameObject.FindGameObjectsWithTag ("FindMe");

                 foreach (GameObject obj in _objects) {
                         float dist = Vector3.Distance (gameObject.transform.position, obj.transform.position);
 
                         distDic.Add (dist, obj);
                 }
 
                 List<float> distances = distDic.Keys.ToList ();
 
                 distances.Sort ();
                         
                 GameObject furthestObj = distDic [distances [distances.Count - 1]];
 
                 // Do something with furthestObj
             
         }
Comment
Add comment · Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image SPIGS · May 25, 2014 at 10:36 PM 0
Share

Thank you! Is there anyway I could access the object with the greatest distance?

avatar image T27M · May 25, 2014 at 10:59 PM 0
Share

Yes, I updated the question with that part. You just take the total count of gameobjects or distances, count them and subtract 1.

 Debug.Log ("Greatest Distance: " + distances [objects.Count - 1]);

Just so you know how this works; List.Count returns the actual number of elements in the List.

Say you have a list with 5 elements, List.Count will return 5. But the list is 0 index meaning it goes 0,1,2,3,4. You want the last item so List.Count -1 = 4.

Hope that helps.

avatar image SPIGS · May 25, 2014 at 11:24 PM 0
Share

if:

 distances [objects.Count - 1];

returns the greatest distance then:

 object[distances.Count - 1];

should return object with greatest distance. However, this seems to only return the object the was created last, not the one with greatest distance. (The objects are randomly instantiated, sorry for not including that in the question. my mistake).

avatar image T27M · May 26, 2014 at 12:05 AM 0
Share

Ah, sorry I skimmed over the comment/question. For some reason I thought you only wanted the distance, the method described above will give you the greatest distance only.

In response to your comment above, the reason that your code gives the last object spawned is because it will always give you the last index. There is no link between the two lists, so it does not work as you expected i.e it will always give the last index. You sorted your list so the lists no longer match up.

Do your objects move?

avatar image SPIGS · May 26, 2014 at 12:36 AM 1
Share

I figured it out!

Using System.Linq I was able to find the greatest value of the distance array without sorting it. Since the distance array is made up of the object's distances in the same order they were in the object array, all I needed to do was find the index of the greatest value of the distance array and apply it to the object array.

Thank you for your help!

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

21 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Distribute terrain in zones 3 Answers

Multiple Cars not working 1 Answer

foreach (or for-next loop) not updating local values 1 Answer

Simple way to make an object go up and down?(Y axis) 1 Answer

Question on Using a Foreach Loop on Nested Children 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges