Target the closest enemy?

So I’m trying to find the enemy that’s closest to the player out of a group of enemies. It doesn’t seem to be targeting properly. What am I doing wrong?

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

public class CombatController : MonoBehaviour {

	GameObject[] enemies;
	GameObject player, target;
	int enemyCount;
	float distance;

	void Start () {

		distance = 100;

		player = GameObject.Find("Player");
	}

	// Update is called once per frame
	void Update () {

		enemies = GameObject.FindGameObjectsWithTag("Enemy");

		for(int i = 0; i < enemies.Length; i++){

			if(Mathf.Abs(Vector2.Distance(player.transform.position, enemies*.transform.position)) < distance){*

_ distance = Mathf.Abs(Vector2.Distance(player.transform.position, enemies*.transform.position));*_

_ target = enemies*;
Debug.Log(target);*_

* player.GetComponent().closestEnemy = target.transform.position;*
* }*
* }*
* }*
}

So I am still learning unity, and C# coding within unity, but I have fixed your code. I’m not sure how to explain it, but you can look at your code versus mine and figure out what I did.

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

public class CombatController : MonoBehaviour
{
    private GameObject[] enemies;
    public Player player; //this assumes that your player script is named "Player"
    private int enemyCount;
    private float distance = 100f;
    private GameObject target;

    void Update()
    {
        enemies = GameObject.FindGameObjectsWithTag("Enemy");

        for (int i = 0; i < enemies.Length; i++)
        {
            if (Vector2.Distance(player.transform.position, enemies*.transform.position) < distance)*

{
distance = Vector2.Distance(player.transform.position, enemies*.transform.position);*

target = enemies*;*

player.targetEnemy = target.transform; // your Player script needs to have a “public Transform targetEnemy;”
}

//this prevents a nasty loop that causes the minimum range for a target to be chosen to become shorter and shorter
if (Vector2.Distance(player.transform.position, enemies*.transform.position) > distance)*
{
distance = Vector2.Distance(player.transform.position, enemies*.transform.position);*
}
}
}
}
After fixing the main problem, I noticed you had a secondary issue in the code. Each time an enemy becomes the target the “Distance” becomes the distance between you and the target. Now this should be good, you want to target the closest enemy. But that distance becomes fixed, so if the original target moves away from the player a new closer target would not be targeted unless it moved closer than the ORIGINAL distance to the first target.