making my turret face the NEAREST enemy

I have written code to find a game object with the tag “enemy” and then rotate my turret in order to face it. However I would like for it to face the nearest target. Therefore I would need to instantiate a list and get all of the transformations sort them and target the first one. However I am unsure of how to go about this. If anyone could help assist me by writing code and commenting out parts and explaining how it works I’d greatly appreciate it.

If anyone could help assist me by
writing code…

Just a heads up that many people won’t be especially receptive to the idea of simply writing code for somebody else.


You might want to consider having the turret only care about things close to it. If it has a trigger collider, you can register enemies entering and leaving the trigger region.

By handling them in that manner, you can have the turret search among only nearby enemies (the ones in a List<> keeping track of them, for example) for whichever one is closest to be the target to face toward.

A few necessary points in this would include:

// C#
void Start()
{
	enemyList = new List<GameObject>();
}

void OnTriggerEnter(Collider other)
{
	if(other.CompareTag("Enemy") && !enemyList.Contains(other.gameObject))
	{
		enemyList.Add(other.gameObject);
	}
}

void OnTriggerExit(Collider other)
{
	enemyList.Remove(other.gameObject);
}

Those are a few of the key points for getting started. Check whether anything comes into range of the turret, ensure they aren’t already detected as being within range, then add them to the list of nearby enemies. When they get out of range, remove them from the list.

Additional measures may include verifying one last time that an enemy is in range before attempting to fire at it (and removing it from the list if it’s not).

FindGameObjectsWithTag() and store them in list of array then use vector3.Distance() to find the nearest one.

i was feeling like writing a code so here you go.

 GameObject[] enemies;
    GameObject player;
    GameObject closestEnemy;

    GameObject FindNearestEnemy () {
        enemies = GameObject.FindGameObjectsWithTag("enemy");

        float minDistance=0;
        int count = 0;

        foreach(GameObject enemyItem in enemies)
        {
            float dist = Vector3.Distance(player.transform.position, enemyItem.transform.position);
            if(count==0)
            {
                minDistance = dist;
                closestEnemy = enemyItem;
                count++;
            }
            else
            {
                if (dist < minDistance)
                {
                    minDistance = dist;
                    closestEnemy = enemyItem;
                }
            }
        }
        return closestEnemy;
    }

Can you help me understand what I’m doing wrong here it doesn’t seem to work

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class Turret : MonoBehaviour
{
GameObject enemies;
GameObject player;
GameObject closestEnemy;
private Vector3 target;

GameObject FindNearestEnemy()
{
    enemies = GameObject.FindGameObjectsWithTag("enemy");

    float minDistance = Mathf.Infinity;
    int count = 0;

    foreach (GameObject enemyItem in enemies)
    {
        float dist = Vector3.Distance(player.transform.position, enemyItem.transform.position);
        if (count == 0)
        {
            minDistance = dist;
            closestEnemy = enemyItem;
            target = closestEnemy.transform.position;

        }
        else
        {
            if (dist < minDistance)
            {
                minDistance = dist;
                closestEnemy = enemyItem;
                target = closestEnemy.transform.position;

            }
        }
    }
    return closestEnemy;

}
private void Start()
{
    InvokeRepeating("FindNearestEnemy", 0f, 0.5f);
    target = closestEnemy.transform.position;
}

}
@Eno-Khaon