Unity freezing/crashing when i use a while statement but not if

the code works fine if i use a if statement but i want the player to keep moving when you press a button not just move once so i thought a while statement would work but it just crashes unity

using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public Rigidbody2D myrigidbody;
    public int playerspeed;
    void Update()
    {
        while (Input.GetKeyDown(KeyCode.A) == true)
        {
            myrigidbody.velocity = Vector3.left * playerspeed;
        }
        while (Input.GetKeyDown(KeyCode.D) == true)
        {
            myrigidbody.velocity = Vector3.right * playerspeed;
        }
    }
}

It crashes because while loop needs both statements true and false. Otherwise will be always true and this cause the crash. Your code is wrong. You don’t have to check is Input true like that.
Change it to:

if (Input.GetKeyDown(KeyCode.A))
{
     myrigidbody.velocity = Vector3.left * playerspeed;
}

same for D key.

Then if you want your player to move longer or shorter, play with Drag in Rigidbody component.

while require yield return null to break the cycle and not freeze the game, so it’d be something like:

while (Input.GetKeyDown(KeyCode.A) == true)
{
    myrigidbody.velocity = Vector3.left * playerspeed;
    yield return null;
}

But for the simplest and most efficient way I’d recommend working with Input.GetAxis("Horizontal) instead:

float horizontal = Input.GetAxis("Horizontal");
myrigidbody.velocity = horizontal * playerspeed;

It’ll save you all that headache as it returns 1 when D or RightArrow is pressed and it’ll return -1 when A or LeftArrow is pressed, and it returns 0 when none of the keys mentioned before are pressed.

I think you got it wrong. What you expect to happen, the sequence of movements, is done by the Update function. It will execute the commands (in this case, a small movement in one direction), end and repeat again after a small fraction of seconds. This is done by all the objects in the scene, which also have commands running inside an Update function, and by several other things that are running in the background, one at a time in sequence. By using “while” you have paralyzed the execution of all software within this loop.
A simple “if” instead of “while” solves the problem. In Unity, there are specific ways and situations in which you can use “while”, but in general it is better to avoid it.