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): using System.Collections; using System.Collections.Generic; using UnityEngine; public class Jumps : MonoBehaviour { Rigidbody2D rb; public float JumpForce = 10f; void Jump() { rb.velocity = Vector2.up * JumpForce; } // Update is called once per frame void Update() { if(Input.GetKeyDown(KeyCode.Space)) { Jump(); } } }
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): private void Start() { rb = GetComponent<Rigidbody2D>(); }