# How to check for the nearest gameObject in OverLapCircleAll?

Hi, I am making a top down 2d roguelike game. I have made pickup gameObjects for weapons. They spawn weapons as the children of the player. This function is doing stuff.

``````public void SpawnWeapon()
{
GameObject player = GameObject.FindGameObjectWithTag("Player");
Instantiate(weaponPrefab, weaponAttachment.position, weaponAttachment.rotation, player.transform);
Destroy(gameObject);
}
``````

It Instantiates the weapon prefab under player. To call this function, the player has OverLapCircleAll which checks for all game objects in weapon pickup layer and then call their SpawnWeapon() function.

``````Collider2D[] isNearWeapon = Physics2D.OverlapCircleAll(gameObject.transform.position, findRange, weaponPickupLayer);
for (int i = 0; i < isNearWeapon.Length; i++)
{
isNearWeapon*.GetComponent<WeaponPickup>().SpawnWeapon();*
``````

}
The problem is that if there are two different weapon pickups laying near each other, then the OverLapCircleAll spawn both of them. So i want to spawn the one which is the nearer and the spawning of one weapon inhibits the spawning of other. One approach I took is to make a bool which check if the player has one weapon equipped. But it doesnâ€™t work when two pickups are both entering the OverLapCircleAll together and both weapons are spawned. But I want to spawn the nearest one and not other one.

This may not be the most efficient way but it definitely works:

``````Collider2D[] isNearWeapon = Physics2D.OverlapCircleAll(gameObject.transform.position, findRange, weaponPickupLayer);

// Set to first found
Collider2D nearestWeapon = null;
float shortestDistance = Mathf.infinity;

for (int i = 0; i < isNearWeapon.Length; i++)
{
if (Vector3.Distance(transform.position, isNearWeapon*.transform.position) < shortestDistance)*
``````

{
shortestDistance = newDist;
nearestWeapon = isNearWeapon*;*
}
}

if (nearestWeapon != null)
nearestWeapon.GetComponent().SpawnWeapon()
The Reason it may not be the most efficient is because if there are lots of these around you it does a distance check with each one.
Note: This should almost never be noticeable in GamePlay