Need help locking movement for a character while attack animation,.using while function.

Hello!

I’m a Unity noob. I have successfully implemented animations for jumping, running and attacking to a character, but I want to disable movement while the attack animation is playing. This is the relevant code I used for the horizontal movement and attack. The solutions I’ve read haven’t really helped me, but I have an idea to accomplish what I want.

public float Speed;

private Rigidbody2D Rigidbody2D;
private Animator Animator;
private float Horizontal;

private void Start()
    {
        Rigidbody2D = GetComponent<Rigidbody2D>();
        Animator = GetComponent<Animator>();
    }

private void Update()
    {
        Horizontal = Input.GetAxisRaw("Horizontal");
        if (Horizontal < 0.0f) transform.localScale = new Vector3(-1.0f, 1.0f, 1.0f);
        else if (Horizontal > 0.0f) transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
       
        Animator.SetBool("Run", Horizontal != 0.0f);
        
        
        if (Input.GetKeyDown(KeyCode.F))
           {
               Attack();
           }
        
       //This is the "solution" I tried, but didn't work. It's an analog for .IsPlaying()            from the animation component.
       while (Animator.GetCurrentAnimatorStateInfo(0).IsName("CharacterAttack") == true)
          {
              Speed = 0.0f;
          }
    }

private void Attack()
    { 
        //The trigger for the animator that kick the attack animation.
        Animator.SetTrigger("Attack");
    }

private void FixedUpdate()
    {
        Rigidbody2D.velocity = new Vector2(Horizontal * Speed, Rigidbody2D.velocity.y);
    }
    }

I had hoped that a “while” would work, but it doesn’t. There’s no error, but I would like to know how to implement this idea correctly.

First, you can NEVER do a while() loop in Unity without making it a coroutine AND putting a yield return null; inside the loop; Unity is single-threaded from your perspective. See link below.

Two general ways of locking out motion while some animation is in progress:

Closed-loop way: use Animation Events or actively query the animation state to decide when the animation is done

Open-loop way: lock out the behavior for an amount of time you pre-determine to match the animation (if you change the animation you must change the time).

Here is some timing diagram help: