I am trying to find the closest enemy to the player that touches/enters trigger collider that extends forward from of the Player. I have stored the Enemy distances inside an array (called enemyArray) and would now like to sort them into ascending order to find the one closest to the Player (which will then be assigned as the next target).
I was wondering if anyone could recommend a way to sort these distances. I have seen mention of the Array.Sort() method and OrderBy() but am not too sure how to implement these and whether they require any namespaces to be included. Also, I'm using C#.
Any help would be greatly appreciated.
Owen's answer is good! The doc page on finding objects by tag even has a closest enemy example: http://unity3d.com/support/documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html?from=index
There's also another unity answers question very similar to this: http://answers.unity3d.com/questions/25842/get-closest-enemy.html
Answer by Owen Reynolds
May 03, 2012 at 06:07 PM
You don't need to sort just to find the closest. If you type "closest enemy" into the Unity search bar, you'll see some working code to find the smallest thing in an array/list.
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a user guide.
If you are a new user, check out our FAQ for more information.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
For troubleshooting common problems with Unity 5.x Editor (including Win 10).
Answers and Comments
5 People are following this question.
Trying to sort an array. What's wrong here?
Sorting a jagged list based on 2nd entry
Sorting variable names by their values.
How to sort get components?
How do you sort a dictionary by value?