Run-Time Error:
NullReferenceException: Object reference not set to an instance of an object
Shooting Script.ForceFire () (at Assets/Scripts/Shooting Script.js:170)
Shooting Script.Update () (at Assets/Scripts/Shooting Script.js:108)
Function Causing Error:
function ForceFire () {
audio.PlayOneShot(shotSound); // play the shot sound
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width * 0.5, Screen.height * 0.5, 0));
if (Physics.Raycast(ray, hit, 100)){
var particleClone = Instantiate(bloodPrefab, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(particleClone.gameObject, 2);
hit.transform.SendMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReciever);
}
}
Complete Code:
You have to ensure that the raycast has actually hit something before you use it.
RaycastHit objects will still be created, regardless of if it actually resulted in a collision. As a result, you must check to see if it’s actually referencing anything before you begin to do anything with it.
function ForceFire () {
audio.PlayOneShot(shotSound); // play the shot sound
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width * 0.5, Screen.height * 0.5, 0));
if (Physics.Raycast(ray, hit, 100)){
var particleClone = Instantiate(bloodPrefab, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(particleClone.gameObject, 2);
if(hit.transform) {
hit.transform.SendMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReciever);
}
}
}
If the Raycast failed (IE it returned false), then hit.transform would be null. That’s why you’re getting a NullReferenceException. hit exists, because you set it to the output of the Raycast, however hit.transform does not exist, because the Raycast failed and hit nothing.