Before updating to Windows 10 you may need to return your Pro license. More information here

Need recommendation for a sorting method for Enemy distances from Player (Ascending) - C#


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.

more ▼

asked May 03, 2012 at 05:06 PM

avatar image

227 107 74 79

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

May 03, 2012 at 06:43 PM Matt-
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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.

more ▼

answered May 03, 2012 at 06:07 PM

avatar image

Owen Reynolds
27.9k 5 39 105

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

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

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments



asked: May 03, 2012 at 05:06 PM

Seen: 1290 times

Last Updated: May 05, 2012 at 04:18 PM