There will be many Situation where you have to find the nearest Enemy or nearest object from a player or a object.
For this this below code is useful ;
void Update()
{
Collider[] c = Physics.OverlapSphere(transform.position, 20);
Transform t = GetClosestEnemy(c);
print("Nearest Object Name" + t.gameObject.name);
}
Transform GetClosestEnemy(Collider[] enemies)
{
Transform tMin = null;
float minDist = Mathf.Infinity;
Vector3 currentPos = transform.position;
foreach (Collider t in enemies)
{
float dist = Vector3.Distance(t.transform.position, currentPos);
if (dist < minDist)
{
tMin = t.transform;
minDist = dist;
}
}
return tMin;
}
Comments
Post a Comment