x


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.

more ▼

asked May 03 '12 at 05:06 PM

asimov gravatar image

asimov
172 34 37 40

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 '12 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 '12 at 06:07 PM

Owen Reynolds gravatar image

Owen Reynolds
19.5k 2 8 66

(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

By RSS:

Answers

Answers and Comments

Topics:

x637
x80
x63

asked: May 03 '12 at 05:06 PM

Seen: 948 times

Last Updated: May 05 '12 at 04:18 PM