Get Closest Target - Unity [ENG]

hello in this video I will show you how to sort your targets based on distance.

So if you want to know what target is closest to your AI or your player you

will be able to find out.

So I have created a 3d project and created a

player made out of a capsule, it also has a nose to see which we are going.

I've created a floor and three enemy objects and giving them a red material to make them easier to see

The player also has character controller and a simple

Player Controller script that just lets you move about on the in the scene

Let's begin by placing our enemies in a new layer

and then we will create a distance comparer

this is what we will use to make the sorting and it needs to derive

from IComparer.

For this we need using system collections and also using system

let's implement the interface

we will need a reference to our the thing we want to compare

distance to for instance our player or something

and we will get reference to this in the constructor

and in this compare this is where we will do is actually sorting when this is executed we will get two objects and we need to

convert these to colliders because we will do overlapping spheres check and

get the colliders.

and then we shall calculate the distance and we can either use vector three

distance or use square instead which is cheaper

and now we just need to make the comparison and return the result

like so, now let's go head over to unity and put this to use so we need to create a

new script, oh sorry

let's call it sense

and we need a radius and a layer mask for what layers we want to check

and let's make it easy so we can see the check radius in the editor.

Let's put this to use in update, let's just print the order the targets based on distance.

in the debug log just to know it's working

So we are going to check and sort our targets when we press space button.

So this will return an array of colliders if they are any inside our check radius

here we also need to using System.Collections if I'm not mistaken to get the

oh just system to get Array.Sort in which we send in our array and what

comparer we want to use.

so we want to use our distance comparer and send in

the transform of whatever component we put the sensor script on and then we just

need to print the colliders. They will be in order

after this is executed.

So let's save and head over to unity.

So let's place our sense component on our player

put down a radius

and let's use the enemy layer.

so sphere is closest then cube.

now cube then sphere then cylinder.

and last but not least, cylinder, cube and sphere.

So it works, excellent.

This is just one of the ways you can sort based on distance you can also check out using delegates or

LINQ, and that's all for this video thank you