Animation when you press key

Hello!
Sorry for my english -)
Help to write code.

Needed:
We press the key - it will become animated, release the key - the animation stops.

I wrote the code, but it does not work as expected:
When you press key the animation starts. When the key is released, it does not stop

      if (Input.GetKey(KeyCode.RightArrow))// if pressed right
        {
                //Should play an animation running right
                anim.SetFloat("Run", Mathf.Abs(runSpeed)); // Play the animation runs
                transform.eulerAngles = new Vector3(0, 0f, 0); // For rotation in the opposite direction sprite
                transform.Translate(runSpeed * Time.deltaTime, 0, 0); // run (runSpeed = 1f)
        }
        
        
        if (Input.GetKey(KeyCode.LeftArrow)) if pressed left
        {
                
                anim.SetFloat("Run", Mathf.Abs(runSpeed)); // Play the animation runs
                transform.eulerAngles = new Vector3(0,180f,0); // For rotation in the opposite direction sprite
                transform.Translate(runSpeed * Time.deltaTime, 0, 0); // run (runSpeed = 1f)
        }

From Russia with love :slight_smile:

I think you are looking for GetKeyDown and GetKeyUp. This will check to see if the key has been pressed down/up and will only return true once per button press.

You also need a way to stop the player moving. Then you can do something like this.

if (Input.GetKeyUp(KeyCode.LeftArrow) || Input.GetKeyUp(KeyCode.RightArrow))
        {
            StopRunning();
        }

My working version

void Run()
    {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            //Должна сыграть анимация бега вправо
            anim.SetFloat("Run", Mathf.Abs(runSpeed));
            transform.eulerAngles = new Vector3(0, 0f, 0);
            transform.Translate(runSpeed * Time.deltaTime, 0, 0);

        }

        // Если кликаем на экран - игрок бежит влево
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            //Должна сыграть перевернутая анимация бега вправо
            anim.SetFloat("Run", Mathf.Abs(runSpeed));
            transform.eulerAngles = new Vector3(0, 180f, 0);
            transform.Translate(runSpeed * Time.deltaTime, 0, 0);
        }

        if (Input.GetKeyUp(KeyCode.LeftArrow) || Input.GetKeyUp(KeyCode.RightArrow))
        {
            anim.SetFloat("Run", currentSpeed);
        }
    }