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.