My jump script doesn't work every time

Hey I am trying to write a jump script, the problem is that when I press the P key sometimes the character jumps and sometimes it doesn’t. I would appreciate any help I can get.

Here is the code:

	public void Update()
{
	

	if (Controller.isGrounded) {
		if (Input.GetKeyDown (KeyCode.P)) {
			vSpeed = JumpSpeed;

		}
	} 



	vSpeed -= Gravity * Time.deltaTime;
	MoveDirection.y = vSpeed;


}

Try using a rigidbody and AddForce:

public void Update() {
    if(Controller.grounded) {
         if(Input.GetKeyDown(KeyCode.P))
             rb.AddForce(Vector3.up * jumpSpeed * Time.deltaTime) ;
    }
}

No error, just doesn’t jump

Make sure you have a rigid body on your character and it has a mass of 1 then make a script and name it Controller with this script.

using UnityEngine;

public class Controller : MonoBehaviour
{
    public float jumpPower = 5;
    private bool grounded;

    Rigidbody rbody;
    private void Start()
    {
        rbody = this.GetComponent<Rigidbody>();
    }
    void Update()
    {
        if (!grounded && rbody.velocity.y == 0)
        {
            grounded = true;
        }
        if (Input.GetKeyDown(KeyCode.P) && grounded == true)
        {
            rbody.AddForce(transform.up * (jumpPower*100));
            grounded = false;
        }
    }
}

It isn’t perfect because if spammed you can double jump but it works and hopefully it can help you and it’ll be further improved.

Hope this helps!