- Home /
Why am I getting a NullReferenceException ?
I am raycasting on an enemy prefab I have. The enemy has a rigidbody on it. the prefab is tagged "Ground Enemy". I am getting a NullReferenceException from the raycast. here is my code:
var hit : RaycastHit;
if (Physics.Raycast(rayorigin.position, turretBall.forward, hit)) {
if (hit.rigidbody.tag == "Ground Enemy") {
rigidbody.SendMessage("TakeDamage", myDamageAmount, SendMessageOptions.DontRequireReceiver);
}
}
I am new to using raycasting. To my understanding though I shouldn't be getting any feedback unless the ray is hitting an object with a rigidbody with a tag == "Ground Enemy" and if that is the case I don't understand why it is getting a null reference...
Answer by robertbu · Apr 16, 2014 at 05:40 AM
On line 4, you are using 'rigidbody.SendMessage(). This will attempt to use a rigidbody of the game object the script above is attached to. I believe you want:
hit.rigidbody.SendMessage("TakeDamage", myDamageAmount, SendMessageOptions.DontRequireReceiver);
Note you are probably safer for what you are doing here to use 'hit.collider.tag' and 'hit.collider.SendMessage()'. Not all game object hit have a rigidbody, but all object hit must have a collider.
You are right, hit.collider works much better, thank you!