Unity freezes when I run animation. How do I fix this?

I can run the game fine and the idle animation works fine but as soon as I run the walking animation (the trigger is the “W” key) the whole unity editor freezes, everything I can’t even close the tab without the task manager.
Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class AnimationScript : MonoBehaviour
{
    const float charactarAnimationSmoothTime = .1f;
    NavMeshAgent agent;
    private Animator anim;
    void Start()
    {
        agent = GetComponent <NavMeshAgent>();
        anim = GetComponent <Animator>();
    }
    void Update()
    {
        float speedPercent = agent.velocity.magnitude / agent.speed;
        anim.SetFloat("speedPercent", speedPercent, charactarAnimationSmoothTime, Time.deltaTime);
        while (Input.GetKeyDown(KeyCode.W))
        {
            anim.CrossFade("HumanoidWalkFINAL", 0.1f);
        }
        if (Input.GetMouseButtonDown(0))
        {
            anim.CrossFade("HumanoidRightCross", 0.1f);
        }
        if (Input.GetMouseButtonDown(1))
        {
            anim.CrossFade("HumanoidLeftCross", 0.1f);
        }
    }
}

@adam_unity566 The while loop is causing it to hang when you press W.

Normally, Input.GetKeyDown(KeyCode.W) would return true for only one frame, but because of the while loop, it keeps looping and never changes frame.


Try changing it to this instead

if (Input.GetKey(KeyCode.W))
{
   anim.CrossFade("HumanoidWalkFINAL", 0.1f);
}

GetKey will return true as long as the button is held down, but it won’t cause a loop