- Home /
I am getting the error of NullReferenceException?
I am getting the error of:
NullReferenceException: Object reference not set to an instance of an object RayCast Shooting.Update () (at Assets/My Scripts/RayCast Shooting.js:13). I do not how to fix this as the game, other than that error, seems to be working fine. Is there anyway to remove/fix this annoying error? I also can't pick a best answer until later this afternoon as I am busy.
My script:
// Prints the name of the object camera is directly looking at
var explosion : Transform;
function Update () {
if (Input.GetButtonDown("Fire1"))
// Get the ray going through the center of the screen
var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));
// Do a raycast
var hit : RaycastHit;
if (Physics.Raycast (ray, hit))
print ("I'm looking at " + hit.transform.name);
Debug.DrawLine (ray.origin, hit.point);
Destroy(hit.collider.gameObject);
if ( hit.collider.gameObject.tag == "Barrels" )
Instantiate(explosion, hit.transform.position, hit.transform.rotation);
}
Answer by DaveA · Jul 25, 2012 at 10:43 PM
if (Physics.Raycast (ray, hit))
{
print ("I'm looking at " + hit.transform.name);
Debug.DrawLine (ray.origin, hit.point);
}
if the raycast failed, the hit.point would not be valid
Thanks I got it working with this code:
var explosion : Transform;
function Update () { if (Input.GetButtonDown("Fire1")) var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0)); var hit : RaycastHit; if (Physics.Raycast (ray, hit)) if( hit.collider.gameObject.tag == "Barrels"){ Debug.DrawLine (ray.origin, hit.point); print ("I'm looking at " + hit.transform.name); Instantiate(explosion, hit.transform.position, hit.transform.rotation); Destroy(hit.collider.gameObject); } else if (Physics.Raycast (ray, hit)){ print ("I'm looking at " + hit.transform.name); Debug.DrawLine (ray.origin, hit.point); Destroy(hit.collider.gameObject); } }