Search Unity

Bug Jump script

Discussion in 'Scripting' started by unity_7J-d1UxblzHGzg, Nov 22, 2022.

  1. unity_7J-d1UxblzHGzg

    unity_7J-d1UxblzHGzg

    Joined:
    Nov 21, 2022
    Posts:
    2
    Im new to unity and c# trying to add jumping and i think im so close but i keep getting the error
    NullRefrenceException: Object refrence not set to an instance of a object

    im not sure whats wrong because i think everything is right

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5.  
    6.  
    7. public class Jumps : MonoBehaviour
    8. {
    9.  
    10.     Rigidbody2D rb;
    11.  
    12.     public float JumpForce = 10f;
    13.     void Jump()
    14.     {
    15.         rb.velocity = Vector2.up * JumpForce;
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.         if(Input.GetKeyDown(KeyCode.Space))
    22.         {
    23.             Jump();
    24.         }
    25.     }
    26.    
    27.  
    28. }
    29.  
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,938
    You never assign anything to your Rigidbody2D; it doesn't magically get a reference to the object's rigidbody.

    You'll want to get a reference to it, either by making it public and assigning the reference in the inspector, or finding it with GetComponent<T> on start.

    Code (CSharp):
    1. private void Start()
    2. {
    3.     rb = GetComponent<Rigidbody2D>();
    4. }
     
  3. unity_7J-d1UxblzHGzg

    unity_7J-d1UxblzHGzg

    Joined:
    Nov 21, 2022
    Posts:
    2
    Thanks, got it working now