Function delay?

So I’m trying to give an enemy game object an attack speed component so that he does damage over time instead of all at once. I tried to use coroutine, here is the script for the enemy below:

public float speed = 1.5f;
public float distanceToPlayer = 1f;
public Vector3 target;
public GameObject player;
public float attackSpeed = 5f;

void Start () {
	target = transform.position;
	gameObject.tag = "Enemy";
}

void Update () {
	//player = GameOject.Find("Player").transform.position;
	if (Vector3.Distance (gameObject.transform.position, Player.currentPosition) > distanceToPlayer) {
		target = Player.currentPosition;
		target.z = transform.position.z;
		transform.position = Vector3.MoveTowards (transform.position, target, speed * Time.deltaTime);
	}	
	else {
		StartCoroutine (PlayerDamage ());
	}
}

IEnumerator PlayerDamage () {
	yield return new WaitForSeconds (5);
	Player.Damage (10f);
}

The Player.Damage() function merely receives the float value and subtracts that from the health, I think this part works fine. However, for some reason the enemy waits the allocated time the first time then executes the function repeatedly instead of starting a new timer. What am I doing wrong?

Most probably the problem is that you are calling the StartCoroutine() function in the Update loop. Basically your else statement inside Update loop keeps starting coroutine every frame.

You can check the Unity documentation for Coroutines to see the examples and find your own way to start the coroutine only once when the distance is close enough to attack. First thing comes to my mind is you can use a boolean to check if the attacking process is finished to start the coroutine again.