NullReferenceException: Object reference not set to an instance of an object

I'm making a game where you can pick up and move objects, which is achieved through the code below. Picking up the objects works fine, but when I try to drop them again, I get the error message "NullReferenceException: Object reference not set to an instance of an object" for the line in between the asterisks below. Can someone explain what I'm doing wrong? It seems to be something to do with the otherThing variable, but I don't see what.

var hasObject: boolean = false;

function Update () 
{       
    var fwd = transform.TransformDirection (Vector3.forward);
    //Defining the travel direction of the raycast vector

    var hit :  RaycastHit;
    //If Raycast collides with something, that becomes the 'hit'

    var LayerMask = 1 << 9;
    //Interacts with 1 layer - Layer 9 - Moveable

    var otherThing : Transform;

    //Draws ray vector in Scene view
    Debug.DrawRay(transform.position, fwd * 50, Color.green);

    //On pressing control, if an object is held, add physics and remove parent
    if (Input.GetButton("Fire2"))
    {
        if (!hasObject)
        {
            if (Physics.Raycast (transform.position, fwd, hit, 50, LayerMask)) 
            {
                otherThing = hit.transform;
                otherThing.rigidbody.isKinematic = true;    
                otherThing.parent = transform;
                //otherThing.rigidbody.mass = 0;
                hasObject = true;
                print("Picked up "+otherThing.gameObject.name+"
");
            }
            else
            {
                print("Nothing to pickup!
");
            }
        } 
        else
        {         
            // ******************
            otherThing.rigidbody.isKinematic = false;
            // ******************
            transform.DetachChildren();
            //otherThing.parent = null;
            hasObject = false;
            print("Dropped "+otherThing.gameObject.name+"
");      
        }
    }
}

I thought I might need an extra 'otherThing = hit.transform;' before the line in question in the else part of the statement, but that didn't seem to work.

Check your code. If hasObject is set, then otherThing isn't set. The reason you're getting a null exception is that you don't set otherThing in that path of execution. I improved your indentation so it becomes clearer.

  • What I think you need to do is declare otherThing as a member variable instead of a local variable. That way the value persist over several calls.
  • When you do this, you no longer need hasObject. You can check if you have otherThing instead.