Hello there Unity Community!
So I have a gun shooting script I made here:
if (lastShot <= Time.time) {
RaycastHit hit = new RaycastHit();
//AudioSource.PlayClipAtPoint(gunSound, transform.position);
audio.Play();
//Debug.DrawRay(transform.Find("BulletSpawn").position, transform.Find("BulletSpawn").TransformDirection(Vector3.forward));
if (Physics.Raycast(transform.Find("BulletSpawn").position, transform.Find("BulletSpawn").TransformDirection(Vector3.forward), out hit)) {
if (hit.distance < distance) {
hit.transform.GetComponent<PhotonView>().RPC("ApplyDamage", PhotonTargets.All, damage);
//hit.transform.SendMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
} else {
//Raycast is a null. (hit terrtain);
}
}
lastShot = Time.time + fireRate;
}
And when I deicde to shoot the terrain (nothing really) then it will give me an error on this line:
hit.transform.GetComponent<PhotonView>().RPC("ApplyDamage", PhotonTargets.All, damage);
Because my hit (RaycastHit) is not hitting any object, it is returning a null which is basically sending the object null “ApplyDamage”.
How can I do a simple if statement to check if the Raycast doesn’t hit anything so I can not send a “ApplyDamage” to that null object.
My guess is that you are hitting a collider on an object that does not have a ‘PhotonView’ component. You can put a Debug.Log() inside the raycast that outputs the name and tag of the hit object to verify. One fix is to check for a null reference of the component;
PhotonView pv = hit.transform.GetComponent<PhotonView>();
if (pv != null) {
pv.RPC("ApplyDamage", PhotonTargets.All, damage);
}