Not registering input when checking input in Update and using input in FixedUpdate

Hi All,

Currently I’m trying to implement jumping but am running into loss of input.

I’m capturing input in the Update method like so:

    private void Update()
    {
        jumpInput = Input.GetKeyDown(KeyCode.Space);
    }

Where jumpInput is a bool member variable.

I’m attempting to use the jumpImput variable in the FixedUpdate method as follows:

    private void FixedUpdate()
    {
        if (jumpInput)
        {
            rigidBody.velocity += new Vector3(0f, -rigidBody.velocity.y + jumpSpeed, 0f);
        }
    }

But something is going awry. The player does not always jump when the space bar is pressed. It seems that sometimes the input is missed.

What is the best way to use input captured from Update in FixedUpdate? How can I prevent the input loss I am experiencing?

Multiple Update calls typically happen between each FixedUpdate call. Space may be detected in an Update, but the consecutive Update resets the variable to false so it doesn’t reach FixedUpdate.

Solution: use OR instead of direct assignment:

void OnEnable()
{
    jumpInput = false;
}

void Update ()
{
    jumpInput |= Input.GetKeyDown(KeyCode.Space);
}

void FixedUpdate ()
{
    if (jumpInput)
    {
        /// ... do something
        jumpInput = false;
    }
}

Note the “|=” instead of “=” in Update. This is the logical OR assignment, equivalent to “jumpInput = jumpInput | Input.GetKeyDown(…)”.