- Home /
How to get the nearest collider, or just a single collider from Physics.OverlapSphere?
So I'm making a game with different unit types moving about in formations, when the player controlled formation gets close to the enemy, it stops and projects an overlapsphere to check for tags - allowing it to see what type of unit it's up against.
So ultimately I need to take the colliders from overlapsphere and return anywhere from one to three strings, detailing the enemy unit's tags.
The problem is that overlapshere produces an array of colliders, and so I'm not sure how to return just one if that becomes an eventuality.
private string CheckEnemies()
{
Collider[] enemyColliders = Physics.OverlapSphere(unit.transform.position, combatRadius);
foreach (Collider col in enemyColliders)
{
string unitName = col.gameObject.tag;
}
return what?
}
C# doesn't have the ability to return two data types to the best of my knowledge, so I'm not sure what to do here.
Answer by alankemp · Feb 09, 2017 at 05:14 PM
Loop through all the colliders and work out how close they are to the unit (use Vector3.Distance). As you look at each collider, if its the closest you have seen, remember it.
Not tested, this might have syntax errors:
Collider GetClosestEnemyCollider(Vector3 unitPosition, Collider [] enemyColliders)
{
float bestDistance = 99999.0f;
Collider bestCollider = null;
foreach (Collider enemy in enemyColliders)
{
float distance = Vector3.Distance(unitPosition.transform.position, enemy.transform.position);
if (distance < bestDistance)
{
bestDistance = distance;
bestCollider = enemy;
}
}
return bestCollider;
}
Just as a note/addition to this answer. This will find the nearest collider based on the origin positions of the objects, not taking into account the bounding size/radius of any of the colliders, so a large sphere that would logically be hit first might not be "nearer" than a smaller collider.
As such you may want to take the bounds of the colliders into account as well.