How to target closest enemy, but with a min/max range

Hey guys,

I’ve been using this cool code and it works great for what I need. I just can’t figure out how to have a minimum range. I don’t want to target something that is too close for example.

Thanks a lot!

public GameObject FindClosestEnemy() 
		{
			GameObject[] gos;
			gos = GameObject.FindGameObjectsWithTag("Copper");
			GameObject closest = null;
			float distance2 = Mathf.Infinity;
			float distance = 15;
			Vector3 position = transform.position;
			foreach (GameObject go in gos) {
				Vector3 diff = go.transform.position - position;
				float curDistance = diff.sqrMagnitude;
				if (curDistance < distance) {
					closest = go;
					distance = curDistance;
				//target = go;

				}
			}
			
			return closest;
		Debug.Log(closest);
			
			
		}

Since you iterate through all possible targets, just add your criteria to the if statement:

public GameObject FindClosestEnemy(float min, float max) 
{
    GameObject[] gos = GameObject.FindGameObjectsWithTag("Copper");
    GameObject closest = null;
    float distance = Mathf.Infinity;
    Vector3 position = transform.position;
    
    // calculate squared distances
    min = min * min;
    max = max * max;
    foreach (GameObject go in gos)
    {
        Vector3 diff = go.transform.position - position;
        float curDistance = diff.sqrMagnitude;
        if (curDistance < distance && curDistance >= min && curDistance <= max)
        {
            closest = go;
            distance = curDistance;
        }
    }
    return closest;
}