Finding nearest game object

How do I find the nearest gameobject (or tag) and determine the distance between that object and the player?

clear explanation or C# only

If you have a lot of objects in your scene that you want to find the distance from but there are other objects you dont care about (for example: many enemies across the map, but you only want to get the enemies near the player) I would recomment using OnTriggerEnter to gather a list of nearby objects first.

You would do this by:

  • creating an empty game object as a
    child of your player
  • attaching a sphere collider and
    setting “trigger” to true
  • setting the radius to a “search
    radius” size determined by you
  • Attach a script to the object with
    OnTriggerEnter and do a check to
    determine if you care about this
    object (compare tag)
  • adding that object to a list.
  • OnTriggerExit remove that object
    from the list.

How to do this can be found here

You could also do a Physics.SphereCast invoking to obtain this list.

The next step would be to read from that list and find the closest object.

        Transform GetClosestEnemy (List<Transform> enemies, Transform fromThis)
            Transform bestTarget = null;
            float closestDistanceSqr = Mathf.Infinity;
            Vector3 currentPosition = fromThis.position;
            foreach(Transform potentialTarget in enemies)
                Vector3 directionToTarget = potentialTarget.position - currentPosition;
                float dSqrToTarget = directionToTarget.sqrMagnitude;
                if(dSqrToTarget < closestDistanceSqr)
                    closestDistanceSqr = dSqrToTarget;
                    bestTarget = potentialTarget;
            return bestTarget;

This will return the closest transform from the list you plug in. So you would need to manually call this function to do the check.

closestEnemy = GetClosestEnemy (yourscript.yourtransformlist, this.transform);

Finding the distance from the closest enemy to the player is a simple Vector3.Distance

Hi, I wrote this 5 minutes ago and it works for me:

    minions = GameObject.FindGameObjectsWithTag("Minion");
    Vector3 shortestDistaceToMinion = new Vector3(1000, 1000, 1000);

    for (int i = 0; i < minions.Length; i++)
        Vector3 distanceToMinion = transform.position - minions*.transform.position;*

if (distanceToMinion.magnitude < shortestDistaceToMinion.magnitude)
shortestDistaceToMinion = transform.position - minions*.transform.position;*
target = minions*;*