how to find the nearest object with a tag unity code example
Example: how to find nearest gameobject unity
void FindClosest()
{
float distanceToClosestEnemy = Mathf.Infinity;
Enemy closestEnemy = null;
Enemy[] allEnemies = GameObject.FindObjectsOfType<Enemy>();
foreach (Enemy currentEnemy in allEnemies)
{
float distanceToEnemy = (currentEnemy.transform.position - this.transform.position).sqrMagnitude;
if (distanceToEnemy < distanceToClosestEnemy)
{
distanceToClosestEnemy = distanceToEnemy;
closestEnemy = currentEnemy;
}
}
if(allEnemies.Length > 0)
{
Ally.transform.position = Vector2.MoveTowards(Ally.transform.position, closestEnemy.transform.position, speedMoving * Time.deltaTime);
}
}