How to maintain speed on the x axis according the last key pressed ?

Hi,

I’m trying to make a cube move on its x axis. The player gets to control the direction according his input (left arrow or right arrow) but I can’t manage to maintain the movement even after he released the button.

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

public class PlayerMovement : MonoBehaviour
{
    public float speed = 5f;

    void FixedUpdate()
    {

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.Translate(-speed * Time.deltaTime, 0f, 0f);
        }

        else if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.Translate(speed * Time.deltaTime, 0f, 0f);
        }
    }

}

here when I stop pressing the left or right arrow, the cube stops but I want it to keep moving (left or right) even after I release the button. Could you help me please ?

Not tested but should work

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class PlayerMovement : MonoBehaviour
 {
     public float speed = 5f;
     private float currentSpeed = 0f;
 
     void FixedUpdate()
     {
 
         if (Input.GetKey(KeyCode.LeftArrow))
         {
             currentSpeed = -1f;
         }
 
         else if (Input.GetKey(KeyCode.RightArrow))
         {
             currentSpeed = 1f;
         }
         transform.Translate(-currentSpeed * Time.deltaTime, 0f, 0f);
     }
 
 }

Oh god… it was that simple…
Thanks a lot ! I appreciate your help