- Home /
Need recommendation for a sorting method for Enemy distances from Player (Ascending) - C#
Hi,
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613071041im_/https://answers.unity.com/themes/thub/images/avi.jpg)