C# : Unity 2D Game Jump (The jump isn't working)

Hello, I tried to jump when I pressed the space bar, but it doesn’t work. What’s the problem?
help me plz…

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

public class PlayerController : MonoBehaviour
{

public float jumpForce = 10f;
public float jumpForce2 = 12f;
private int jumpCount = 0;
private bool isGrounded = false;

Rigidbody2D Rigidbody;
Animator animator;

private void Start() {
    Rigidbody = GetComponent<Rigidbody2D>();
    animator = GetComponent<Animator>();

}

private void Update() {
    PlayerAni_Jump();
}

private void PlayerAni_Jump() {
    
    if (Input.GetKeyDown(KeyCode.Space)&&jumpCount < 3) {
        jumpCount++;
        Rigidbody.velocity = Vector2.zero;
        Rigidbody.AddForce(Vector2.up * jumpForce);
    }
        
    else if(Rigidbody.velocity.y > 0) {
        Rigidbody.velocity = Rigidbody.velocity * 0.5f;
        animator.SetBool("Grounded", isGrounded);
    }
    
}

void OnCollisionEnter2D(Collision2D collision) {
        if(collision.contacts[0].normal.y > 0.7f) {
            jumpCount = 0;
        }

}

Greetings @EZeroE

There are a few things I would change here:

  • Don’t call your Rigidbody2D “Rigidbody”. Even lowercase will cause problems with conflict.
  • You are changing rb.velocity and AddForce in the Update loop when it’s best to do it in FixedUpdate. There are time when this may be OK but this is not one of them.
  • You are setting rb.velocity to zero. That will also set your vertical velocity to zero, which may not be what you want
  • It’s good practice to collect input in Update and save values for processing elsewhere (eg in Fixed Update).

Putting these together (and simplifying your code for demo purposes), the following works for me:

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float jumpForce = 10f;
    private int jumpCount = 0;
    bool jumpPressed = false;
    Rigidbody2D rb;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jumpPressed = true;
        }
    }

    private void FixedUpdate()
    {
        if (jumpPressed && jumpCount < 3)
        {
            Jump();
        }
    }

    void Jump()
    {
        rb.velocity = Vector2.zero;
        rb.AddForce(Vector2.up * jumpForce);
        jumpCount++;
        jumpPressed = false;
    }
}