GetButtonDown not always firing

I have a basic character movement script for a 2d platformer. My problem is that when using “GetButtonDown” the “jump” action only executes about 75% of the time. The rest of the time it completely ignores the input. If I change that to “GetKey(KeyCode.Space)” it works perfect every time, but, I get the bunny-hop effect. Any help is greatly appreciated!

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {
 
 #region Variables
 
 public float speed = 6.0f;
 public float jumpSpeed = 8.0f;
 public float gravity = 9.81f;
 private bool canJump;
 private Vector3 moveDirection = Vector3.zero;
 
 #endregion
 
 
 #region Functions
 
 void Update()
 {
 CharacterController controller = GetComponent<CharacterController>();
 
 if (controller.isGrounded)
 {
 moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, 0);
 moveDirection = transform.TransformDirection(moveDirection);
 moveDirection *= speed;
 
 if (!Input.GetKey(KeyCode.Space))
 {
 canJump = true;
 }
 
 if (Input.GetKey(KeyCode.Space) && canJump == true)
 {
 moveDirection.y = jumpSpeed;
 canJump = false;
 }
 }
 controller.Move(moveDirection * Time.deltaTime);
 moveDirection.y -= gravity * Time.deltaTime;
 
 Debug.Log(controller.isGrounded ? "GROUNDED" : "NOT GROUNDED");
 }
 
 #endregion
}

UPDATE:

I added the debug log to detect if the controller was grounded or not and I noticed that it was flipping back and forth from “grounded” to “not grounded” when I wasn’t even moving or jumping. This looks like the reason that my jump isn’t reliable… any idea why this is happening?

Instead of using FixedUpdate, move your code to Update method. FixedUpdate gets called based on even intervals, the times it ignores your input is the times that it’s not updated/called between those intervals.