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?