- Home /
Question by
In-Visuals · May 31, 2012 at 12:45 PM ·
raycastnullreferenceexception
NullReferenceException in Raycast script
So, I've come up with a script that tells me what I'm looking at and then makes me move toward it when I hold the "Fire1" button. However when I press this button it gives me a NullReferenceException. I can't seem to locate the problem.
The script still works but I would like "not" to get the error report.
I have tried to locate the problem but my brain is failing me it seems. And help would be appreciated!
private var distance : float = 20.0;
var speed : float;
var moveToMe : Transform;
function Update () {
var cam : Transform = Camera.main.transform;
var ray = new Ray(cam.position, cam.forward);
var hit : RaycastHit;
if(Physics.Raycast(ray, hit, distance)){
var moveToMe = hit.transform;
Debug.Log(hit.transform.name);
}
if (Input.GetButton("Fire1") && hit.collider.tag == "Lerpz"){
transform.position = Vector3.Lerp(transform.position, moveToMe.position, Time.deltaTime * speed);
}
Debug.DrawLine(ray.origin, ray.origin + ray.direction * distance);
}
Comment
Best Answer
Answer by whydoidoit · May 31, 2012 at 12:48 PM
Your problem is that the if(Input.GetButton("Fire1")...
isn't inside the if
that checks whether the Raycast hit something - so it happens even if it doesn't. Make it like this:
if(Physics.Raycast(ray, hit, distance)){
var moveToMe = hit.transform;
Debug.Log(hit.transform.name);
if (Input.GetButton("Fire1") && hit.collider.tag == "Lerpz"){
transform.position = Vector3.Lerp(transform.position, moveToMe.position, Time.deltaTime * speed);
}
}
Thank you for your fast reply! This was indeed the problem and it is now fixed.