Please help! NullReferenceException error. Can't find referred to object...

Hello Fellow Cool Dudes and Dudettes!

Thank you for reading my post! I have seen many posts with similar questions (re: NullReferenceException) to mine, but the answers always seemed to be either plugging in a GameObject that was called for in the Inspector, or something similar.

I have taken apart my movement code, splitting it into separate scripts for turning, moving forward, leaning, etc…, trying to find out which one was the culprit, but it turns out they ALL do. It is always the Update method or the FixedUpdate method (I apologize if I’m using incorrect terms… I’m a noob). I am at my wits end! I have no idea what its asking me for!

Below is the error message, as well as my script:

NullReferenceException: Object reference not set to an instance of an object
TurnLR.FixedUpdate () (at Assets/Scripts/TurnLR.cs:36)

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

public class TurnLR : MonoBehaviour
{

    [Header("---Components---")]

    protected Rigidbody _rigidbody;

    UnicycleController _controls;

    #region // Floats --------------

    [Header("---Control Inputs---")]

    [SerializeField] private float turn;
    [SerializeField] private float _turnSpeed = 20f;

    #endregion // ----------------

    private void Awake()
    {

        _controls = new UnicycleController();

        _controls.Gameplay.Turn.performed += ctx => turn = ctx.ReadValue<float>();
        _controls.Gameplay.Turn.canceled += ctx => turn = ctx.ReadValue<float>();

    }

    private void FixedUpdate()
    {

        _rigidbody.AddTorque((turn * _turnSpeed) * _rigidbody.transform.up);    <————— LINE 36

    }

    void OnEnable()
    {
        _controls.Gameplay.Enable();
    }

    void OnDisable()
    {
        _controls.Gameplay.Disable();
    }
}

Thank you again for reading my post! I checked multiple NullReferenceException posts before posting, just to make sure I wasn’t duplicating a previous post. I’m at a loss… Have a great day!

try adding this above that error line (to check if _rigidbody is null)

Debug.Log(_rigidbody);

at least your script is not setting it anywhere.

1 Like

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

https://discussions.unity.com/t/840647/7

As @mgear points out, it’s probably _rigidbody.

1 Like

Thank you both for your speedy replies! I posted this on my lunch break… didn’t expect two replies by the time I got off work. Thank you!!

I assume you were [both] correct! Here is the new error message I got after adding that new line, and the new code:

Null
UnityEngine.Debug:Log (object)
TurnLR:FixedUpdate () (at Assets/Scripts/TurnLR.cs:35)

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

public class TurnLR : MonoBehaviour
{

    [Header("---Components---")]

    protected Rigidbody _rigidbody;

    UnicycleController _controls;

    #region // Floats --------------

    [Header("---Control Inputs---")]

    [SerializeField] private float turn;
    [SerializeField] private float _turnSpeed = 20f;

    #endregion // ----------------

    private void Awake()
    {

        _controls = new UnicycleController();

        _controls.Gameplay.Turn.performed += ctx => turn = ctx.ReadValue<float>();
        _controls.Gameplay.Turn.canceled += ctx => turn = ctx.ReadValue<float>();

    }

    private void FixedUpdate()
    {
        Debug.Log(_rigidbody);  // <------------ADDED LINE
        _rigidbody.AddTorque((turn * _turnSpeed) * _rigidbody.transform.up);
     
    }

    void OnEnable()
    {
        _controls.Gameplay.Enable();
    }

    void OnDisable()
    {
        _controls.Gameplay.Disable();
    }
}

So, now that I know my Rigidbody is null… How do I fix that? Delete it and add it back in? I have a rigidbody on the component, and my script doesn’t call for any other Rigidbodies…

Again, thank you for the help! I’m pretty new, and I only ever got that error message when I forgot to drag something into the inspector.

UPDATE: I just deleted all of my Rigidbodies and all of the joints that held them together, then reapplied them all. It still give me the same error message. Again, I’m new… but how can the Rigidbody be null if it is right there?

When I take all the scripts off my parent object, and all the children, the object falls to the ground and bounces, then topples over. As soon as I add any script that calls for a RIgidbody, I get the problem.

Perhaps I need a RIgidbody on one of my Mesh only children? I never had to do that before…

Thank you for your time!!

Traditionally you make a public field (none of this protected stuff) and drag it in via the inspector.

Alternatively you can do a GetComponent() to find it in Start(), possibly even Awake().

1 Like

Yessir. Thank you so much. I love this community so far. For real.

So, even if the code is on the object with the Rigidbody, I still need to call it?

As you can probably tell, I have no idea what protected means. Public means you can call it from another script (I think) and it shows in the inspector. Private means it doesn’t, but you can use [SerializeField] to see it in the inspector.

No idea what Protected means. I saw it in a tutorial. and I thought it looked cool. Hahaha! Same reason I’ve been a smoker for 20 years. …Stupid peer pressure…

Hahah!! THANK YOU Kurt, and mgear, you are both stellar.

EDIT: your dog looks rad.

UPDATE: Golly. I feel like a right dummy. (isn’t that how the brits say it? like a ‘right’ ___?)

I was missing a Rigidbody on the Cube object I am using as my ground. Since I accidentally assigned a script to it, Unity was searching forever for a Rigidbody that I had no intention of ever placing.

MissingComponentException: There is no ‘Rigidbody’ attached to the “Cube” game object, but a script is trying to access it.
You probably need to add a Rigidbody to the game object “Cube”. Or your script needs to check if the component is attached before using it.
TurnLR.FixedUpdate () (at Assets/Scripts/TurnLR.cs:37)

I was looking at the right script, but on the wrong GameObject. I wish Unity had given me THIS error message LAST NIGHT. Ha. I guess the upside is that this definitely “learnt” me an important lesson.

…Just what that lesson might be? Still up for debate.

THANK YOU AGAIN!!! BOTH OF YOU!!!

There’s back history here. Waaaay back in the days when the earth was a fiery inhospital place, Unity had built-in shortcuts in the MonoBehavior class for a whole range of “stuff you might commonly find on GameObjects.”

Some of these things were .audio for the AudioSource, if present, or .renderer for any object derived from Renderer.

Since Physics is common, they also had one called .rigidbody for exactly what you guessed it to be.

But all those things are gone, deprecated and good riddance, since they were sort of arbitrary warts on the design of the MonoBehaviour class, needless complexities as it were.

Today the only surviving one is .transform, which is an extremely useful shortcut to the ever-present Transform.

1 Like

Kurt, you are awesome.

Quick question on the topic… I am told not to use the Transform to move an object AND the RIgidbody at the same time (AddForce or AddTorque), since that will cause problems. If I use _rb.transform.AddForce(), that is okay, right?

Errr… Just now realizing maybe you’re not supposed to use TRANSLATE to move an object that you are also using the Rigidbody to move through force. That makes more sense. Ha.

Yes, it’s this.

If you have a Rigidbody and physics going, and you move the position (or rotation) via the transform you are going to startle and anger the physics subsystem.

Symptoms of a startled and angered physics system include:

  • missed collisions
  • missed triggers
  • glitchy jerking objects
  • jitter
  • cats living with dogs
  • mass hysteria
1 Like

I’m not about to invite glitchy, jerk items into my life. High school is in my past, and it will STAY in my past. (glitchy jerkING items are still around, just way less frequently than in my teenage life. Ha.)

Hey, almost off the topic, and since you are so helpful and generous with your time, sir… (Did I mention I like that shirt you’re wearing today? Really goes well with your… font.) is AddForce to Translate as AddTorque is to Rotate (or RotateAround)?

I am trying to get my unicycle to rotate at 90 degrees every time you press straight left or straight right on the control stick. If you press halfway, I want it to spin 45 degrees, but if you hold all the way left, I want it to go 90 degrees and then stop.

Meaning, I don’t want it to continually spin. If you want to turn more than 90, you must recenter the joystick, and press left or right again, for another rotation (between 0 - 90 degrees).

Currently using AddTorque to turn, and to spin the wheel. not looking forward to the trial and error of set amounts of AddTorque per joystick pull (not that I even know how to do that anyways)

Thank you Kurt! You’re rad. I appreciate you, sir!