Null Reference Exception on Raycast

var fireSound : AudioClip;
var reloadSound : AudioClip;
var bullets : float;
var reloadTimer : float;
var coolTimer : float;

function Start () {
}

function Update () {
	if (coolTimer) {
		coolTimer -= Time.deltaTime;
		if (coolTimer < 0) {
			coolTimer = 0;
		}
	}
	if (reloadTimer) {
		reloadTimer -= Time.deltaTime;
		if (reloadTimer < 0) {
			reloadTimer = 0;
		}
	}
	if (!bullets) {
		audio.PlayOneShot(reloadSound);
		reloadTimer = 3.0;
		bullets = 30;
	}
	if (bullets && !coolTimer && !reloadTimer) {
		audio.PlayOneShot(fireSound);
		coolTimer = 0.1;
		bullets -= 1;
		var hit : RaycastHit;	
		if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward) * 1000)) {
			if (hit.collider.name == "Character") {
				Health.health -= 1;
			}
		}
	}
}

This script controls the enemy weapon. Everytime I stand in front of the thing, it gives me an error message saying “Object reference not set to an instance of an object”. This is not the first time I’ve had this show up. What is it and how do I fix the issue?

Look at your use of Physics.Raycast. As far as I can tell the variable hit is never set.

We can be a little bit more helpful if you point out the exact line that’s throwing the exception.

I’m guessing that it’s this one:

if (hit.collider.name == "Character") {

I say that because your raycast call doesn’t look like it will populate the hit variable:

var hit : RaycastHit; 
if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward) * 1000)) {

There are many different versions of Physics.Raycast(), each of which has slightly different properties. You might try calling one of the versions which takes a RaycastHit parameter, perhaps like this:

Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), hit, 1000)