Answers for "how to find nearest gameobject unity"

C#
1

how to find nearest gameobject unity

void FindClosest()
    {     
        float distanceToClosestEnemy = Mathf.Infinity;
        Enemy closestEnemy = null;
       //Edit Enemy in the FindObjectsOfType to a component on the object you
       //want to find nearest 
        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 you want to move to nearest object 
       if(allEnemies.Length > 0) 
       {
           Ally.transform.position = Vector2.MoveTowards(Ally.transform.position, closestEnemy.transform.position, speedMoving * Time.deltaTime);

       }
    }
Posted by: Guest on March-08-2021
0

unity find nearest object

Transform GetClosestEnemy(Transform[] enemies)
{
    Transform tMin = null;
    float minDist = Mathf.Infinity;
    Vector3 currentPos = transform.position;
    foreach (Transform t in enemies)
    {
        float dist = Vector3.Distance(t.position, currentPos);
        if (dist < minDist)
        {
            tMin = t;
            minDist = dist;
        }
    }
    return tMin;
}
Posted by: Guest on September-30-2020

Code answers related to "how to find nearest gameobject unity"

C# Answers by Framework

Browse Popular Code Answers by Language