Something not 'up' with my rocket

I am getting a null reference exception in the console. Object reference not set to an instance of an object.

Please help my rocket fly!!!

thanks,

Dave

Hi Dave,

Welcome to our community! :slight_smile:

NullReferenceException means that a reference (“link”) to an instance is missing. Double click on the error message to see to which line in your code it is referring. If you exposed a field in the Inspector, make sure that it’s not empty.

Thank you for the reply Nina. What does it mean to have an exposed field? I am now getting the same error on line 11 as well 24

below is my code.

many thanks

using UnityEngine;

public class Rocket : MonoBehaviour
{
Rigidbody rigidBody;

// Start is called before the first frame update
void Start()
{
    rigidBody.GetComponent<Rigidbody>(); #line11!!!!
}

// Update is called once per frame
void Update()
{
    ProcessInput();
}

private void ProcessInput()
{
    if (Input.GetKey(KeyCode.Space))
    {
        rigidBody.AddRelativeForce(Vector3.up);  #line 24!!!!!!
      
    }
    if (Input.GetKey(KeyCode.A))
    {
        print("Rotating Left");
    }
    else if (Input.GetKey(KeyCode.D))
    {
        print("Rotating Right");
    }
   
}

}

By “exposed field”, I meant a field in the Inspector.

I think I spotted the issue. Ignore line 24 and focus on line 11. What exactly was your idea in Start()? What is that line of code is supposed to do?

Remember you can also look at the lecture code changes via the link in the Resources of each lecture.

Thank you so much!

Fixed it, I just missed that completely! I think I was trying to access it rather than find it.

So to be clear, if Unity couldn’t find rigidbody then it couldn’t link it?

By default, variables of reference types are null. Rigidbody is a reference type, thus rigidBody is null by default. It does not contain a reference (“link”) to any object. You’ll have to explicitedly add one.

In your code, you tried to access a non-existing object assigned to rigidBody. What you actually wanted to do is to assign the returned reference to the variable.

rigidBody = GetComponent<Rigidbody>();

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms