I am getting the error of NullReferenceException?

I am getting the error of:

NullReferenceException: Object reference not set to an instance of an object
RayCast Shooting.Update () (at Assets/My Scripts/RayCast Shooting.js:13). I do not how to fix this as the game, other than that error, seems to be working fine. Is there anyway to remove/fix this annoying error? I also can’t pick a best answer until later this afternoon as I am busy.

My script:

 // Prints the name of the object camera is directly looking at
var explosion : Transform;

function Update () {
 if (Input.GetButtonDown("Fire1"))
    // Get the ray going through the center of the screen
    var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));
    // Do a raycast
    var hit : RaycastHit;
    if (Physics.Raycast (ray, hit))
        print ("I'm looking at " + hit.transform.name);
   Debug.DrawLine (ray.origin, hit.point);
 Destroy(hit.collider.gameObject);
 if ( hit.collider.gameObject.tag == "Barrels" )
 Instantiate(explosion, hit.transform.position, hit.transform.rotation);
}

1 Answer

1

if (Physics.Raycast (ray, hit))
{
print ("I’m looking at " + hit.transform.name);
Debug.DrawLine (ray.origin, hit.point);
}

if the raycast failed, the hit.point would not be valid