Prevent Jump Spamming

Hi! I’m working on a code that prevents the player spamming Jump, I came up with a script that should do just what I want but it seems that it works only every second time?? Note that in my game the jumps can differ in length, height and duration, that’s why I went with this approach. I would appreciate any help with my code or even ideas for a better one. Thanks!

     //jumping based on current speed
     if (controller.Grounded == true && Input.GetAxisRaw("Vertical") > 0 && afterjump == false)
     {
         player.AddForce(new Vector2(player.velocity.x - player.velocity.x * jumpdistance, jumpheight), ForceMode2D.Impulse);
         Invoke("afterJumpFunction", 0.01f);
     }
     //finding time spot when player lands after jump
     if (controller.Grounded == true && afterjump == true)
     {
         Invoke("jumpWait", jumpwait);
     }
 }

 // Custom functions
 void afterJumpFunction()
 {
     afterjump = true;
 }
 void jumpWait()
 {
     afterjump = false;
 }

Note: jumpwait is just a float I’m setting in the inspector.

Idk if this’ll solve the issue but I’d suggest doing something like

private void Update()
    {
        if (controller.Grounded == true && Input.GetAxisRaw("Vertical") > 0 && canJump)
        {
            player.AddForce(new Vector2(player.velocity.x - player.velocity.x * jumpdistance, jumpheight), ForceMode2D.Impulse);
            StartCoroutine(JumpDelay());
        }
    }

    IEnumerator JumpDelay()
    {
        canJump = false;
        yield return new WaitForSeconds(jumpwait);
        canJump = true;
    }

This will create a “jumpwait” delay from the moment you do a successful jump and since you can’t jump when you’re not grounded you’ll only be able to jump once you land again. You probably don’t want to create any delays blocking input once the user has landed on the ground.