Making a script send a message to the "closest" enemy

I am developing a script which enables a player to attack GameObjects tagged “enemy”. The issue I am trying to resolve is the ability to produce damage towards any closest “Enemy” object, instead of one GameObject after another. At this stage, I am only able to murder a specific tagged object, instead of any closest tagged object. Here is a chunk of the script related to my issue (the center of problem is marked in arrows):

function Update () {

InvokeRepeating(“FindClosestEnemy”, 0, scanFrequency);
}

function FindClosestEnemy() : GameObject {

 var gos : GameObject[];
 gos = GameObject.FindGameObjectsWithTag("Enemy");
 var closest : GameObject;
 var distance = Mathf.Infinity;
 var position = transform.position;
 
 for (var go : GameObject in gos) {
 var diff = (go.transform.position - position);
 var curDistance = diff.sqrMagnitude;
 
 if (curDistance < distance) {
 closest = go;
 distance = curDistance;
 
 SendMessage("CloseEnemy", closest); //State name variable?
 
       }
    }
 return closest;
}

 function CloseEnemy(closest)
    
    {

→ closest : String = gameObject.name;

→ Target = GameObject.FindWithTag(“Enemy”);

 var distance = Vector3.Distance(Target.transform.position, transform.position);
 
 var dir = (Target.transform.position - transform.position).normalized;
 
 var direction = Vector3.Dot(dir, transform.forward);

 
 if (Input.GetKeyDown("q")){
 
 if ( distance < 5){
 
 if ( direction > 0){
 
 var script = Target.GetComponent(EnemyHealthDraw);
 
 script.punchDmg(PunchDamage); 
 
 }
 
 }
 
 } 

}

There is a function which is triggered after SendMessage(“CloseEnemy”, closest). I was happy with this, because print(closest); registered the name of the “closest” enemy object, however I failed to convert the variable “closest” into a string, which could be used for GameObject.Find(string);. In place of string, I inserted “enemy”. If you can answer this problem, it will help me a lot! Thanks.

After running the loop in FindClosestEnemy, your gameObject variable closest is the nearest enemy. You can completely delete the two lines you have marked and replace them with: Target=closest;.

Secondly, that’s a standard “Price is Right” loop. It looks at enemies one at a time, making closest always be the nearest enemy so far. It can set closest multiple times, as it sees more enemies. So, the SendMessage should be moved to after the loop, instead of being in it.