Raycast and SendMessage malfuction

I’m trying to cast a ray that sends a message to a script telling it to run damage functions.

 var hit : RaycastHit;

	var fwd = transform.TransformDirection(Vector3.forward);

	

	if (Physics.Raycast (rayReference.position, fwd, 100)) {

		print("There is something in front of the object!");

		Debug.DrawLine (transform.position, hit.point);

		hit.collider.gameObject.BroadcastMessage("Hurt4", damage4, SendMessageOptions.DontRequireReceiver);

		}

}
function Hurt4(damage4 : float){
Health -= damage4;
print("We're hit!");
if(Health <= 0){
Death();
}
}

However, even when the ray registers a hit, the message doesn’t get sent or work. I’ve tried attaching colliders and rigidbodies to ensure that it’s hitting, but it just won’t work. It constantly says: Object reference not set to an instance of an object

Can anyone give me a reason or solution for this?

your not filling the hit variable.

take a look at the docs, you want the overload with the out RaycastHit and put your hit variable in there.

edit: Physics.Raycast(rayReference.position, fwd, hit, 100)

THANK YOU!

Man, missing hours of sleep made me overlook that.

yep :slight_smile: just as a side note, if you avoid using RaycastHit as a member, you would have at least got a warning/error about using a uninitialized variable. Probably best to keep RaycastHit’s as local variables when possible.