monster attacking player

Hello! sorry for bad english :smiley:

I trying to monster deals damage to player with attack animation,
but it keeps damaging player without any delay.

thanks a lot if you give me any advice!

	void Update () {
		Attack ();
	}
		
	void Attack (){
		if (transform.position.z < 4) {
			StartCoroutine ("Damaging");
			animation.Play ("attack");
				}
		}

	IEnumerator Damaging()
		{
		yield return new WaitForSeconds (1.0f);
		health -= Random.Range (1, 2);
		}
}

set a timer, and while Damaging set this value to the time it takes the animation, then on the update, if this timer is not 0 it wont attack until it reaches 0

void Update () {
   if(timerAttacking <=0)
      Attack ();
   else
      timerAttacking -= Time.deltaTime;
}
float timerAttacking = 0f;
void Attack (){
   if (transform.position.z < 4) {
      StartCoroutine ("Damaging");
      timerAttacking = 2f;
      animation.Play ("attack");
   }
}

bool attacking = false;

    void Update () {
       Attack ();
    }
 
    void Attack (){
       if (transform.position.z < 4 && !attacking) {
         StartCoroutine ("Damaging");
         animation.Play ("attack");
          }
       }
 
    IEnumerator Damaging()
       {
       attacking = true;
       yield return new WaitForSeconds (1.0f);
       health -= Random.Range (1, 2);
       attacking = false;
       }
}

the problem is youโ€™re just creating a whole bunch of coroutines since you have no check to stop one being created every frame. just add a boolean that gets set to true before the yield and false after. have this check in the initial call. Set the yield to the length of the animation though