- Home /
Raycasting null object reference error
I'm fairly new to scripting in Unity, and I'm creating a game where I want to change cameras when an object is clicked on. I'm not focusing on the code for changing cameras at the moment, but instead detecting if the object has been clicked on. I've looked around and modified some code from other places to use Raycasting. Here is my code:
function FixedUpdate () {
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var Hit : RaycastHit;
if(Physics.Raycast(ray, Hit, 1000)){
if(Hit.collider == null){
Debug.Log("miss");
}
else if(Hit.collider.tag == "document") {
Debug.Log("clicked");
}
}
}
I keep getting NullReferenceException: Object reference not set to an instance of an object.
I have the script attached to the first person camera in the scene. Please Help!
To say for sure I'd have to see the script in it's entirety as well as the error message Unity is throwing. You can then pinpoint what line of code Unity is complaining about.
Pasting in the error from the console and/or indicating what line the error is occurring on would speed along a solution.
If you've changed the tag on the main camera to something other than '$$anonymous$$ainCamera', this code will fail with a null reference.
Answer by HuskyPanda213 · Apr 04, 2014 at 01:00 AM
The problem is you are checking if the hit collider is null, which is not what you want. The if(physics.Raycast) part checks if it hits something, so you are checking something that will never happen. Here is how I would do it. Two notes: First, do not call it in the FixedUpdate. Second, your naming is inconsistant, a raycasthit named Hit, with capital, but a ray without capital?
Here is how it should look:
function Update () {
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if(Physics.Raycast(ray, Hit, 1000)){
if(Hit.collider.tag == "document"){
Debug.Log("hit");
}
else {
Debug.Log("You hit something else.");
}
}
else{
Debug.Log("miss");
}
}
Thanks, that fixed it! Now I have no errors except it's not picking up the document. It says either miss or you hit something else. I think it might be a problem with my tagging. I named the object in the hierarchy view as 'document'. Is that all I had to do, or do I need to tag it, because when I look at the inspector panel it has a drop down menu that says Tag.