Script that stores gameobject hit by raycast keeps getting a NullReferenceException error.

I’ve looked at other threads about storing gameObjects as variables when hit by a ray, and I believe a duplicated the answers correctly, but I can’t get this script to work.

The idea is to have one box above another, each one with this script attached. The boxes then raycast and store each other as variables so another function can edit their properties.

Lines 26 and 37 keep giving me a NullReferenceException: object reference not set to an instance of an object.

var boxColor : Color;
private var boxUp : GameObject;
private var boxDown : GameObject; 


function Start () 
{
	renderer.material.color = boxColor;
	
	UpBoxRay ();
	DownBoxRay ();
}

function Update ()
{

}

function UpBoxRay ()
{
	var hit : RaycastHit;
	
	if (Physics.Raycast (transform.position, Vector3.up, 100))
	{
		renderer.material.color = Color.magenta;
		boxUp = hit.collider.gameObject;
	}
}

function DownBoxRay ()
{
	var hit : RaycastHit;
	
	if (Physics.Raycast (transform.position, Vector3.down, 100))
	{
		renderer.material.color = Color.green;
		boxDown = hit.collider.gameObject;
	}
}

I have a suspicion that my problem may be related to using the same script on multiple objects. When I take one box with the script on it and put an default sphere on the top and the bottom I only get one null reference.

Anyway, I’m stumped.

Hit is defined but nothing is loaded into it so hit.collider.gameObject causes a NUL reference. At least that is my guess.

It has to do with how the raycast call is made.
Here is the reference. Unity - Scripting API: Physics.Raycast

So perhaps you want the second example

if (Physics.Raycast(transform.position, -Vector3.up, out hit, 100.0F))

Now hit should have something in it.

It may be helpful to use Debug.Log(“hit is ==>” + hit); to see what is happening.

Similarly to what JeffreyD said. Changing lines 24 and 34 to

if (Physics.Raycast (transform.position, Vector3.up, hit, 100))

seemed to do it.

Having an out before the hit would return an error. Also, I’m not sure what the F after the ray length does, but that got me on the right track.