How to apply an animation for the attack?

i have this part of a script

   IEnumerator Attack()
{

    enemyCanAttack = true;

    if (!enemyIsAttacking)
    {

        enemyIsAttacking = true;

        while (enemyCanAttack)
        {

            lastShotFired = Time.time;

            

            yield return new WaitForSeconds(attackTime);

        }

    }

}

how to fix the part of the script so it can play an attack animation and deal damage to character?

Use bools to see if the enemy is close to the player, if it is, set attack bool to true, if the player gets away, just use false!

public float lookRadius = 10f;
Transform target;
NavMeshAgent agent;
public Animator anim;
public float velocity;
private void Start()
{
    target = PlayerManager.instance.player.transform;
    agent = GetComponent<NavMeshAgent>();
}

private void Update()
{
    

    velocity = agent.velocity.magnitude;
    float distance = Vector3.Distance(target.position, transform.position);
    if(distance <= lookRadius)
    {
        agent.SetDestination(target.position);
        if (distance <= agent.stoppingDistance)
        {
            //Attack player
            AttackPlayer();
            FaceTarget();
        }
        else
        {
            StopAttackPlayer();
        }
    }
    if(velocity > .1)
    {
        anim.SetFloat("speed", 1f);
    }
    else
    {
        anim.SetFloat("speed", 0f);
    }
}
void FaceTarget()
{
    Vector3 direction = (target.position - transform.position).normalized;
    Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
    transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
}

void AttackPlayer()
{
    anim.SetBool("attack", true);
}

void StopAttackPlayer()
{
    anim.SetBool("attack", false);

}