How to stop the attack function if player leaves the check sphere?

The AI will find the player and once within range, attack. If the player leaves the attack range, the AI continues the shoot animation and just slides along the ground. I would like the AI to stop the attack and go back to chase. hey, I got this far with out asking a question.

using UnityEngine;
using UnityEngine.AI;


public class EnemyAI : MonoBehaviour
{

    public NavMeshAgent agent;

    public Transform player;

    public Transform alienBulletSpawn;

    private float damage = 10;

    public LayerMask whatIsGround, whatIsPlayer;

    private Animator anim;

    //States
    public float attackRange;
    public bool playerInAttackRange; 

    private void Awake()
    {
        player = GameObject.Find("Player").transform;
        agent = GetComponent<NavMeshAgent>();
        anim = GetComponent<Animator>();
        
    }

    private void Update()
    {
        anim.SetFloat("Speed", 1f);
        playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);


        if (!playerInAttackRange) EngagePlayer();
        if (playerInAttackRange) AttackPlayer();
        
    }

    void EngagePlayer()
    {
        agent.SetDestination(player.position);

    }
        
    void AttackPlayer()
    {
        agent.SetDestination(transform.position);
        transform.LookAt(player);
        anim.SetTrigger("Attack");
        

        RaycastHit hit;
        if (Physics.Raycast(alienBulletSpawn.transform.position, alienBulletSpawn.transform.forward, out hit))
        {   
            PlayerHealth playerHealth = hit.transform.GetComponent<PlayerHealth>();
            if (playerHealth != null)
            {
                playerHealth.PlayerDamage(damage);
            }
        }
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, attackRange);   
    }



}

Well your animator has 2 states. Something for your walk animation and something for your attack animation. You currently change from one into the other when you “attack” by setting the trigger “Attack”.

Now you simply need a state transition in your animator from the attack animation back to the walk animation. Add another trigger, smth like “StartWalk” and set the attack → walk transition to trigger when “StartWalk” is set. Then add this call to your EngagePlayer function:

  anim.SetTrigger("StartWalk");