destroy gameobject with ray


I am trying make a scipt to destroy gameobject which is hit by ray that I am casting. Ray casting is working good, but when it hits gameobject it makes this error:

NullReferenceException: Object reference not set to an instance of an object
Movement.Update () (at Assets/Scripts/Movement.js:13)

I cant figure it out.
#pragma strict

var fwd;
var hit : RaycastHit;

function Update () {
		fwd = transform.TransformDirection (-Vector3.up);
		Debug.DrawRay(transform.position, fwd,;
		if (Physics.Raycast (transform.position, fwd, 10)) {

This error is telling you that hit has no value assigned to it. This is because you never assign a value to it.

There is an overload of Physics.Raycast() with the following signature:

static function Raycast(origin: Vector3, direction: Vector3, hitInfo: RaycastHit, distance: float = Mathf.Infinity, layerMask: int = DefaultRaycastLayers): bool;

You can use it by making the following change:

//  if (Physics.Raycast (transform.position, fwd, 10)) {
if (Physics.Raycast (transform.position, fwd, hit, 10)) {

After making this change you will be passing hit into the Raycast() function where it will be populated with information about the RaycastHit (if one occurs).