RaycastHit not sending message

I have an Object A that shoots a laser towards Object B. Object B has a multi-segment shield that I would like to receive damage when hit by the laser. I’m using RaycastHit to determine which segment of the shield was hit. Object B has a script that applies damage to itself when the RaycastHit sends it a message.

Here’s the code from Object A:

public bool shieldCheck () {
    Vector3 laserSource = origin.position;
    Vector3 target = destination.position;
    Vector3 laserDirection = Vector3.Normalize (target - laserSource);
    dist = Vector3.Distance (origin.position, destination.position);
    int layerMask = 1 << 10;
    layerMask = ~layerMask;
    RaycastHit hit;
    shieldStatus = Physics.Raycast (origin.position, laserDirection, dist, layerMask);
    if (shieldStatus == true) {
    hit.transform.SendMessage ("hitByLaser");
    	return true;
    } else
    	return false;

Here’s the function from Object B that applies the damage:

void hitByLaser () {
		if (shieldHealth <= 0f) {
			Destroy (gameObject);
		} else
			shieldHealth -= damage;

When I run the game, I get an error on the following line from Object A:

hit.transform.SendMessage ("hitByLaser");

The error message says, “NullReferenceException: Object reference not set to an instance of an object.” What reference do I need to make? I thought that when Raycast hit something, RaycastHit gives me the reference to the object that was hit. The code works fine without the RaycastHit portion, but that means no damage is applied to the shield. How do I fix my RaycastHit code?

Welcome to Unity Answers!

Are you familiar with function overloading? There are about ten different versions of Physics.Raycast, each of which has a slightly different set of arguments. For the most part, it’s pretty mundane: do you care how far you’re casting, which layers you’re casting on, etc?

Some versions of raycast have an “out” or “pass-by-reference” parameter to populate a RaycastHit. The particular version you’re calling does not – which might be handy, if you didn’t need that data, but in my experience you almost always want it.

If you type Physics.Raycast( in MonoDevelop, you should get an autocomplete list that will show you all of the possible signatures. I’m pretty sure you want this one:

    shieldStatus = Physics.Raycast(origin.position, laserDirection, out hit, dist, layerMask);

Thanks, rutter! This fixed the issue. For some reason, every answer I googled led me to believe that the order of parameters was:

shieldStatus = Physics.Raycast(origin.position, laserDirection, dist, out hit, layerMask);

Anytime I tried that, it would give me errors on the parameters. Your solution worked perfectly. Thanks again!