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?