Hi, I’m new to Unity and C#, and I’m trying to make a simple script for 2D jumping. Right now, I’m not trying to tie in any animation or anything, just trying to get my player gameObject to jump when I press the corresponding key.
I get the following error message: “NullReferenceException: Object reference not set to an instance of an object
JumpScript.FixedUpdate () (at Assets/scripts/JumpScript.cs:27)”
…and the following line of code is highlighted: “rb.AddForce(Vector2.up * jumpHeight);”
My script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JumpScript : MonoBehaviour
{
public float jumpHeight;
public bool isGrounded;
Rigidbody2D rb;
void Start()
{
this.GetComponent<Rigidbody2D>();
}
void OnCollisionEnter2D(Collision2D coll)
{
isGrounded = true;
}
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.W))
{
if (isGrounded)
{
rb.AddForce(Vector2.up * jumpHeight);
isGrounded = false;
}
}
}
}