# Why do we use Mathf.Infinity to find closest target ?

Hello, I’ve been trying to understand how to go to the closest target gameObject among several of them, so I searched for a while. Although I succesfully implemented the code in my project, I still don’t get why do we use Mathf.Infinity in order to achieve this goal.

My problem is that, since we’re calculating a distance between two points, all distances will be less than Infinity, so how does the script know which enemy to target ?

Here are the solutions I found:

Example 1:

Example 2:

Example 3:

Example 4:

It’s nothing specifically to do with the subject of the post here, just a way to find a minimum value.

If you want to iterate through a set of values, looking for the minimum then you’ve got to start with a “high” value you don’t expect to find normally so it’s for when you check if the one you just found is “closer”. Infinity is always going to be bigger. You could change your logic to add a flag that indicates if this is the first one and just use it then skip the closer to last result check but that’s messy.

There’s also “float.MaxValue” you can use which is the largest value you can possibly store in a float (single) and isn’t likley something you’ll find normally.

Again though, this is just an algoritm on numbers finding the lowest value.

I’m not going to dig through any tutorial. It seems your question though is how to you associate the value with a specific target. It should be clear that if you find a “closer” target with the check then you store a reference to that. When done, you’ll have the closest value and the target associated with it.

Not sure if this is what you’re asking, it’s so obvious an answer I feel I missed the point maybe.

How many enemies you got? You can try using my distance comparator for point lists, here . But in order for them to work as intended, you either check a few points which you can enter directly as argument, or you’re supposed to prepare a list (or array) of them in advance.

I can also help you customize this approach so that it searches through an array of transforms which you can maybe get with FindGameObjectsWithTag or a similar technique.

If your enemies are numerous but usually likely to be outside some maximum range – i.e. you are consistently wasting time by observing/measuring distance to enemies that are too far away anyway – you should probably use a dedicated spatial algorithm to optimize the solution. Though you’d probably have a hard time doing this considering you’re still learning.

Regarding your original question, I believe MelvMay told you everything there is to know in the 1st reply.